在mouseenter上使用javascript旋转div并将它们旋转回mouseleave上的原始位置

时间:2018-06-10 03:19:21

标签: javascript jquery html5 css3

我的目标是在鼠标进入时使div旋转,并在鼠标离开时将其旋转回原始位置。当我只与一个div交互时,它可以正常工作,但当我尝试将鼠标悬停在其他div上时,它会开始出现故障。

JS

$(document).ready(function(){

var blocks = document.getElementsByClassName('block-item');

for (var i = 0, max = blocks.length; i < max; i ++) {
    blocks[i].onmouseenter = blocks[i].onmouseleave = handler;
}

var startRotate = function(blackFrame, blackFrameAngle) {
// ...
};

var startRotateBack = function(blackFrame, blackFrameAngle) {
// ...
};

function handler(event) {

  // If mouse enters start rotating clock-wise
  if (event.type == 'mouseenter') {

        // Calculate angles
        var blackFrame = event.target.querySelectorAll('.block-frame')[0];
        var blackFramePos =         getComputedStyle(blackFrame).getPropertyValue('transform');
        var blackFrameValues = blackFramePos.split('(')[1],
        blackFrameValues = blackFrameValues.split(')')[0],
        blackFrameValues = blackFrameValues.split(',');
        var a = blackFrameValues[0];
        var b = blackFrameValues[1];
        var radians = Math.atan2(b, a);
        if ( radians < 0 ) {
            radians += (2 * Math.PI);
        }
        var blackFrameAngle = Math.round( radians * (180/Math.PI));

    // Start rotating
    startRotate(blackFrame, blackFrameAngle);

  }

  // If mouse leaves stop rotating clock-wise and start rotating back
  if (event.type == 'mouseleave') {

  clearInterval(RotateFrame)
  // ...
  // ...
  // Start rotating back
  startRotateBack(blackFrame, blackFrameAngle);

  }

}

});

完整代码位于jsfiddle http://jsfiddle.net/fw3ma9ej/2/

1 个答案:

答案 0 :(得分:0)

我们可以通过使用CSS过渡属性来解决它,并在悬停时更改元素的旋转角度。

您可以在此处查看示例:http://jsfiddle.net/j10y98w2/1/

transform: rotate(45deg);
transition: transform 5s ease-out;
&:hover {
  transform: rotate(315deg);
}