我的代码的目的是使瞳孔跟随用户的光标方向。这是我遵循的代码:https://codepen.io/J-Roel/pen/wWGNQN,但是它是用jQuery编写的,因此我已将其转换为普通js:

eyeHandler(event) {
  let eye = this.$refs.eye
  let x = (eye.getBoundingClientRect().left) + (eye.clientWidth / 2)
  let y = (eye.getBoundingClientRect().top) + (eye.clientHeight / 2)
  let rad = Math.atan2(event.pageX - x, event.pageY - y)
  let rot = (rad * (180 / Math.PI) * -1) + 180
  eye.style.webkitTransform = 'rotate(' + rot + 'deg)'
  eye.style.mozTransform = 'rotate(' + rot + 'deg)'
  eye.style.msTransform = 'rotate(' + rot + 'deg)'
  eye.style.transform = 'rotate(' + rot + 'deg)'
}


这是我添加事件监听器的地方:

created() {
  window.addEventListener('mousemove', this.eyeHandler)
}


但是它没有按预期工作:


当我向右移动光标时,瞳孔下降得非常缓慢。
当我向左移动时,它会上升。


猜猜,我将代码转换为错误的方式。

最佳答案

我的建议是:



document.querySelectorAll('.move-area').forEach(function(ele) {
    ele.addEventListener('mousemove', function(event) {
        var eye = document.querySelectorAll(".eye");
        var x = (eye[0].offsetLeft) + (eye[0].offsetWidth / 2);
        var y = (eye[0].offsetTop) + (eye[0].offsetHeight / 2);
        var rad = Math.atan2(event.pageX - x, event.pageY - y);
        var rot = (rad * (180 / Math.PI) * -1) + 180;
        eye.forEach(function(ele) {
            ele.style['-webkit-transform'] = 'rotate(' + rot + 'deg)';
            ele.style['-moz-transform'] = 'rotate(' + rot + 'deg)';
            ele.style['-ms-transform'] = 'rotate(' + rot + 'deg)';
            ele.style['transform'] = 'rotate(' + rot + 'deg)';
        });
    });
})

.move-area{/*normally use body*/
    width: 100vw;
    height: 100vh;
    padding: 10% 45%;
}
.container {
    width: 100%;
}
.eye {
    position: relative;
    display: inline-block;
    border-radius: 50%;
    height: 30px;
    width: 30px;
    background: #CCC;
}
.eye:after { /*pupil*/
    position: absolute;
    bottom: 17px;
    right: 10px;
    width: 10px;
    height: 10px;
    background: #000;
    border-radius: 50%;
    content: " ";
}

<section class="move-area">
    <div class='container'>
        <div class='eye'></div>
        <div class='eye'></div>
    </div>
</section>

09-19 10:07