2010-05-28 23 views
6

我試圖在鼠標左鍵關閉時將鼠標移動事件綁定到div,並在釋放時解除綁定。這段代碼應該是相當自我解釋的。用jQuery綁定mousedown函數中的mousemove

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> 

螢火蟲說,綁定方法上內handleMouseDown和handleMouseUp變量SBAR不確定。 螢火蟲控制檯打印<div class="statusbar">爲行評論//螢火蟲

我做錯了什麼,可能綁定mousedown和mouseup時......但是什麼?! 我使用jQuery v1.4.2,如果有幫助?

回答

6

.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 :)

+0

啊 - 我明白了。非常感謝! – colinjwebb 2010-05-28 10:28:10

+0

@colinjameswebb - 這是一個優化的版本,不需要傳遞'sbar',使用'this'(當前上下文)給你的優勢:) http://jsfiddle.net/JLtT3/1/ – 2010-05-28 10:33:38

相關問題