调整窗口大小时如何取消绑定/关闭jQuery事件 [英] How to unbind/off jQuery event when window resize

查看:78
本文介绍了调整窗口大小时如何取消绑定/关闭jQuery事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在窗口> 490时删除一个jquery事件.但是,当窗口小于490px时,unblind()或off()元素不会取消激活的动作.为什么是这样?有谁知道使选择返回其原始状态的任何方法?

I am trying to delete a jquery event when the window gets >490. However, the unblind() or off() elements do not deactivate the action activated when the window gets smaller than 490px. Why is this? Does anyone knows any method to make a selection return to its original state?

$(document).ready(function(){

    $(window).resize(function(){
    if ($(window).width()<490) {
    $("#shown").unbind().click(function(){
        event.preventDefault();
        $("body div hidden").toggle('slow');
    });
    }

    else if ($(window).widht()>=490) {
        $("#shown").unbind();
        $("body div hidden").unbind();
    }
    });
});

</script>

推荐答案

这是您实现所需目标的方法,下面的代码将根据屏幕大小取消隐藏事件的绑定.

Here is how you can achieve your desired, the below code will unbind the hide event based on the screen size.

$(document).ready(function()
{
var eventPresent = false;
$(window).resize(function()
{
 console.log("current width : ", $(window).width());
 
if ($(window).width()<490 && eventPresent == false) 
{ 
 $("#shown").unbind().click(function(event)
 {
   event.preventDefault();   
   $("#divText").toggle('hide');
 });
 eventPresent  = true;
}    
else if ($(window).width()>=490 && eventPresent == true) 
{            
   $("#shown").unbind();
   $("#divText").show()  
   eventPresent = false;     
 }
  });
});

 

 <script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>

 <a id="shown">click me to hide text</a>
   
<div id="divText">
                
You can not toggle me if screen is more than 490 px wide
         
</div>
 

P.S以全页模式运行代码段.

P.S Run the snippet in full page mode.

这篇关于调整窗口大小时如何取消绑定/关闭jQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆