如何使用jquery旋转鼠标滚轮上的元素

How to rotate element on mousewheel using jquery?

本文关键字:元素 鼠标 何使用 jquery 旋转      更新时间:2023-09-26

我想当我鼠标向上时,盒子无限旋转,鼠标向下也是但是当我做的时候它只是从20旋转到-20。我该怎么做呢?

https://jsfiddle.net/eunjin/n4ckfxw2/1/

$(window).bind('mousewheel', function(e) {
    if (e.originalEvent.wheelDelta > 0) {
        $(".box").animate({ rotate: 20 }, {
            step: function(now, fx) {
                $(this).css('-webkit-transform', 'rotate(' + now + 'deg)'); 
                $(this).css('-moz-transform', 'rotate(' + now + 'deg)');
                $(this).css('transform', 'rotate(' + now + 'deg)');
            }
        });
    } else {
        $(".box").animate({ rotate: -20 }, {
            step: function(now, fx){
                $(this).css('-webkit-transform', 'rotate(' + now + 'deg)'); 
                $(this).css('-moz-transform', 'rotate(' + now + 'deg)');
                $(this).css('transform', 'rotate(' + now + 'deg)');
            }
        });
    }
});

您需要声明一个变量并在其中存储旋转值。在mousewheel事件中改变它并将元素动画到目标值

var rotate = 0;
$(window).bind('mousewheel', function(e){       
    // Increase/decrease value of rotate
    rotate += e.originalEvent.wheelDelta > 0 ? 20 : -20;
    // Animate rotate of element
    $(".box").stop().animate({rotate:rotate},{
        step:function(now){
            $(this).css({
                '-webkit-transform':'rotate('+ now +'deg)',            
                '-moz-transform':'rotate('+ now +'deg)',
                'transform':'rotate('+ now +'deg)'
            }); 
        }
    });
});

var rotate = 0;
$(window).bind('mousewheel', function(e){	
  rotate += e.originalEvent.wheelDelta > 0 ? 20 : -20;
  $(".box").stop().animate({rotate:rotate},{
    step:function(now){
      $(this).css({
        '-webkit-transform':'rotate('+now+'deg)',            
        '-moz-transform':'rotate('+now+'deg)',
        'transform':'rotate('+now+'deg)'
      }); 
    }
  });
});
body { 
    padding: 10px 100px 10px 100px 
}
.box {
  width:100px; 
  height:100px;  
  border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

你可以在demo

中测试结果