【问题标题】:jquery mousemove how to stopjquery mousemove如何停止
【发布时间】:2013-09-03 10:29:30
【问题描述】:

我有这个小提琴http://jsfiddle.net/JqBZb/193/ 我希望我的对象仅在按下红色方块时移动,但是当用户释放鼠标时我无法删除 mousemove 动作。之后它仍然移动。

HTML:

<div class="pointer">
    <div class="marker"></div>
</div>

CSS:

.marker {
    background:#ED1C24;
    height:2px;
    right:0;
    position:absolute;
    top:35px;
    width:7px
}
.pointer {
    height:72px;
    position:absolute;
    top:82px;
    width:72px;
    border:1px solid red;
 left:100px;
}

JAVASCRIPT:

var img = $('.pointer');

var offset = img.offset();

function mouse(evt) {
    var center_x = (offset.left) + (img.width() / 2);
    var center_y = (offset.top) + (img.height() / 2);
    var mouse_x = evt.pageX;
    var mouse_y = evt.pageY;
    var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
    var degree = (radians * (180 / Math.PI) * -1) + 90;
    img.css('-moz-transform', 'rotate(' + degree + 'deg)');
    img.css('-webkit-transform', 'rotate(' + degree + 'deg)');
    img.css('-o-transform', 'rotate(' + degree + 'deg)');
    img.css('-ms-transform', 'rotate(' + degree + 'deg)');
}

img.mousedown(function (e) {
    $(document).mousemove(mouse);
}).mouseup(function (e) {
    e.stopPropagation();
})

原来的轮播脚本由这个答案https://stackoverflow.com/a/10235298/1168944提供

【问题讨论】:

  • 有点好一点,如果鼠标悬停时你仍然悬停在框上,它会停止:jsfiddle.net/JqBZb/195
  • 如果您使用的是旧版本的 jQuery,请使用 bindunbindfiddle.

标签: jquery mousemove


【解决方案1】:

将此添加到您的脚本中...

$(document).mouseup(function() {
    $(document).off("mousemove", mouse);
});

每当您释放鼠标按钮时,它都会取消绑定 mousemove 事件处理程序。

http://jsfiddle.net/JqBZb/201/

为了适应off(),我也将其更新为更高版本的jQuery。

【讨论】:

  • 有效!非常感谢!
【解决方案2】:

创建一个布尔值来检查 mouseDown 是否为真/假

 var mouseDown = false;
 if(mouseDown ==true){
   //move code
 }

DEMO

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多