jQuery - 绑定到调整大小事件的函数无法一致工作
我有一些代码充当菜单的点击切换。我只希望代码在窗口宽度低于 768px 时运行,因此我将其包装在 if 语句中,该语句计算窗口宽度。我将此函数绑定到页面调整大小事件和页面就绪。它有时有效,但有时无效。调整结果面板的大小几次,您就会明白我的意思...
I have some code that acts as a click toggle for a menu. I only want the code to run if the window width is under 768px, so I wrapped it in an if statement, that calculates the window width. I bound this function to the page resize event and page ready. It works some of the time but not others. Resize the results panel a few times and you'll see what I mean...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不是关键问题,但是:
jQuery("#nav-btn a.togglemenu")
应该是jQuery("#nav a.togglemenu")
您已经添加了
aaMenus
函数内的单击处理程序,因此这一行:...正在运行该函数,并在每次调整窗口大小时添加一个新单击处理程序。 如果单击处理程序已添加偶数次,您同时打开和关闭,没有可见的结果。即使添加了奇数次,您也会连续运行切换数百次,从而导致巨大的延迟。
您需要做的就是将该单击事件处理程序从您的函数中取出:
http://jsfiddle.net/mblase75/LyUzr/10/
Not the key issue, but:
jQuery("#nav-btn a.togglemenu")
should bejQuery("#nav a.togglemenu")
You've added the click handler inside the
aaMenus
function, so this line:...is running the function, and adding a new click hander, every time the window is resized. If the click handler has been added an even number of times, you're toggling on and off at the same time, with no visible result. Even if it's been added an odd number of times, you're running the toggle up to hundreds of times in a row, resulting in a huge delay.
All you need to do is take that click event handler out of your function:
http://jsfiddle.net/mblase75/LyUzr/10/