jQuery:当div变得可见时如何为其绑定事件?
我有一个 div 元素:
。标签数据
当此 div 变得可见时(获取 display: block;
),如何绑定自定义事件?
而且我想在这个 div 变得不可见时绑定一个事件(获取 display: none;
)。
我想用 jQuery 来做这件事。
编辑: 我正在使用 ajax 内容制作简单的选项卡。我希望仅当该选项卡可见时才通过 ajax 更新该选项卡上的内容。
I've got a div element:<div id="tab1">
.
Tab data
</div>
How to bind a custom event when this div becomes visible (gets display: block;
)?
And also I'd like to bind an event when this div becomes invisible (gets display: none;
).
I'd like to do this in jQuery.
Edit:
I'm making simple tabs with ajax content. I want the content on this tabs to be ajax-updated only when the tab is visible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据可见性启动和停止 AJAX 更新。您可以使用
.is()
来返回 TRUE 或 FALSE:visible
:这是一个定时器的简单示例,当它不可见时停止。请注意,当数字不可见时,数字不会继续增加:
jsFiddle 示例
当然,在上述情况下,也许您的情况下,简单地交替打开和关闭更新会更直接:
jsFiddle 示例
Start and stop the AJAX update based on the visibility. You can use
.is()
to return a TRUE or FALSE for:visible
:Here is a simple example of a timer that stops when it is invisible. Note that the numbers don't keep increasing when they're not visible:
jsFiddle example
Of course, in the above case, and maybe your case, it's more straight forward to simple alternately turn the update on and off:
jsFiddle example
让事件始终绑定到 div,但在事件内部,执行如下操作:
现在,仅当元素对用户可见时才会触发事件。
Have the event always bound to the div, but inside the event, do something like the following:
Now your event will only be triggered if the element is visible to the user.
我找到的解决方案是在选择选项卡时启动
focus
事件。然后我捕获这些
focus
和blur
事件:The solution I found was to fire up
focus
event when the tab is selected.And then I catch these
focus
andblur
events: