【问题标题】:Binding mousemove within mousedown function with jQuery使用jQuery在mousedown函数中绑定mousemove
【发布时间】:2011-04-27 16:48:21
【问题描述】:

我试图在鼠标左键按下时将 mousemove 事件绑定到 div,并在释放鼠标左键时取消绑定。这段代码应该是不言自明的。

function handleMouseDown(e, sbar){
    if (e.button == 0){
        console.log(sbar); //firebug
        sbar.bind('mousemove', function(event){
            handleMouseMove(event, sbar);
        });
    }
}

function handleMouseUp(e, sbar){
    sbar.unbind('mousemove');       
}

function handleMouseMove(e, sbar){
    // not sure it this will work yet, but unimportant
    $(".position").html(e.pageX);
}

$(document).ready(function (){

    var statusbar = $(".statusbar");

    statusbar.mousedown(function(event){
        handleMouseDown(event, this);
    });

    statusbar.mouseup(function(event){
        handleMouseUp(event, this);
    });

});

HTML 的重要部分如下所示

<div id="main">
    <div class="statusbar">
        <p class="position"></p>
    </div>
</div>

Firebug 说在handleMouseDown 和handleMouseUp 中的变量sbar 上未定义绑定方法。 firebug 控制台打印出 &lt;div class="statusbar"&gt; 注释行 //firebug

我做错了什么,可能是在绑定 mousedown 和 mouseup 时......但是什么?! 我正在使用 jQuery v1.4.2,是否有帮助?

【问题讨论】:

    标签: javascript jquery javascript-events


    【解决方案1】:

    .bind().unbind() 是 jQuery 函数,所以你需要稍微调整一下,而不是这样:

        sbar.bind('mousemove', function(event){
            handleMouseMove(event, sbar);
        });
    

    你需要这个(把它包装成一个 jQuery 对象):

        $(sbar).bind('mousemove', function(event){
            handleMouseMove(event, sbar);
        });
    

    .unbind() 也一样:

    $(sbar).unbind('mousemove');
    

    You can see a working demo with only those corrections here :)

    【讨论】:

    • 啊——我明白了。非常感谢!
    • @colinjameswebb - 这是一个优化版本,无需传递sbar,使用this(当前上下文)对你有利:) jsfiddle.net/JLtT3/1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多