0

我正在使用凝视按钮,但是当点击事件被触发时,该函数被执行了两次。请参阅下面的代码片段。

var number = 0;

document.getElementsByTagName('a-sphere')[0].addEventListener('click', function(){
    alert('You\'ve clicked the sphere ' + (++number) + ' times.');
});
<script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
<a-scene>
    <!-- this is my object that must execute a click event when looked -->
    <a-sphere position="0 0 -7" color="red">
    </a-sphere>

    <!-- camera -->
    <a-camera look-controls wasd-controls cursor="maxDistance: 30; fuse: true">
        <!-- progress bar -->
        <a-entity position="0 0 -3" geometry="primitive: ring; radiusOuter: 0.07;radiusInner: 0.05;" material="color: cyan; shader: flat"
            cursor="maxDistance: 30; fuse: true">
            <!--<a-cursor color="red"></a-cursor>-->
            <a-animation begin="click" easing="ease-in" attribute="scale" fill="backwards" from="0.1 0.1 0.1" to="1 1 1" dur="150"></a-animation>
            <a-animation begin="fusing" easing="ease-in" attribute="scale" fill="forwards" from="1 1 1" to="0.1 0.1 0.1" dur="1500"></a-animation>
        </a-entity>
    </a-camera>
</a-scene>

如何防止两次单击对象的这种情况?它必须在单击时触发一次。

4

1 回答 1

0

我已经做了一个解决方法来防止这个问题

var number = 0;

document.getElementsByTagName('a-sphere')[0].addEventListener('click', function(){
    if(this.getAttribute('data-clicked') === null || this.getAttribute('data-clicked') === 'false') {
        this.setAttribute('data-clicked', 'true');
        alert('You\'ve clicked the sphere ' + (++number) + ' times.');
    }
    else {
        this.setAttribute('data-clicked', 'false');
    }
});
<script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
<a-scene>
    <!-- this is my object that must execute a click event when looked -->
    <a-sphere position="0 0 -7" color="red">
    </a-sphere>

    <!-- camera -->
    <a-camera look-controls wasd-controls cursor="maxDistance: 30; fuse: true">
        <!-- progress bar -->
        <a-entity position="0 0 -3" geometry="primitive: ring; radiusOuter: 0.07;radiusInner: 0.05;" material="color: cyan; shader: flat"
            cursor="maxDistance: 30; fuse: true">
            <!--<a-cursor color="red"></a-cursor>-->
            <a-animation begin="click" easing="ease-in" attribute="scale" fill="backwards" from="0.1 0.1 0.1" to="1 1 1" dur="150"></a-animation>
            <a-animation begin="fusing" easing="ease-in" attribute="scale" fill="forwards" from="1 1 1" to="0.1 0.1 0.1" dur="1500"></a-animation>
        </a-entity>
    </a-camera>
</a-scene>

当然,这不是防止问题的好方法,但它确实有效。

于 2017-05-19T10:06:39.863 回答