![](/img/trans.png)
[英]How do I make the javascript resize event handler happen only after the user stops resizing the window?
[英]Event handler not working after moving element on window resize
我是網絡編程的新手,目前正在建立一個響應式網站。 在window resize事件中,右側BAR通過insertBefore()和appentTo()方法移動。 但在那之后,sideBar上的事件處理程序不再起作用了。
一個簡單的事件處理方法:
$('#sideBar').mouseover(function(){
alert("hello");
});
僅當我刪除時才有效:
function setlayout(){
if($(window).width() <= 720){
$('#sideBar').insertBefore('#footer');
}else{
$('#sideBar').remove().appendTo('#navbar');
}
};
$(window).on('resize load', function(){ setlayout() });
如何使事件處理程序工作?
當您的側邊欄被刪除然后動態添加到頁面時,您必須以這種方式選擇它:
$(document).on('mouseover', '#sideBar', function() {
alert('hello');
});
jQuery在加載時附加事件,因此如果從頁面中刪除元素,則刪除附加到它的所有事件處理程序。 這就是為什么你必須通過在$(document)
元素上調用它們來委托事件。
使用JSFiddle示例 。
嘗試:
$('#sideBar').appendTo('#navbar').remove();
如果刪除節點,則此節點的處理程序也將刪除。 所以你應該重新綁定事件,或者只使用事件委托。 @Hulothe的方式是事件代表。
$(document).on('mouseover', '#sideBar', function() {
alert('hello');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.