jQuery:当 div 变得可见时,如何为它绑定一个事件? [英] jQuery: How to bind an event for the div when it becomes visible?
问题描述
我有一个 div 元素:<div id="tab1">标签数据</div>
.
I've got a div element:
<div id="tab1">
Tab data
</div>
.
当这个div可见时如何绑定自定义事件(获取display:block;
)?
How to bind a custom event when this div becomes visible (gets display: block;
)?
我还想在这个 div 变得不可见时绑定一个事件(获取 display: none;
).
And also I'd like to bind an event when this div becomes invisible (gets display: none;
).
我想在 jQuery 中执行此操作.
I'd like to do this in jQuery.
我正在制作带有 ajax 内容的简单标签.我希望此选项卡上的内容仅在选项卡可见时进行 ajax 更新.
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.
推荐答案
根据可见性启动和停止 AJAX 更新.您可以使用 .is()
来为 :visible
返回 TRUE 或 FALSE强>:
Start and stop the AJAX update based on the visibility. You can use .is()
to return a TRUE or FALSE for :visible
:
var timer; // Variable to start and top updating timer
// This if statement has to be part of the event handler for the visibility
// change of selector..... so there might be more straight forward solution
// see the last example in this answer.
if ($(selector).is(":visible"))
{
// Start / continue AJAX updating
timer = setInterval(AJAXupdate, 1000);
} else
{
// Stop AJAX updating
clearInterval(timer);
}
这是一个在不可见时停止的计时器的简单示例.请注意,当它们不可见时,数字不会继续增加:
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:
(function() {
var switcher; // variable to start and stop timer
// Function / event that will be started and stopped
function count() {
$("div").html(1 + parseInt($("div").html(), 10));
}
$(function() { // <== doc ready
// Start timer - it is visible by default
switcher = setInterval(count, 1000);
$("input").click(function() {
$("div").toggle(); // Toggle timer visibility
// Start and stop timer based on visibility
if ($("div").is(":visible"))
{
switcher = setInterval(count, 1000);
} else
{
clearInterval(switcher);
}
});
});
}());
jsFiddle 示例
<小时>当然,在上述情况下,也可能是您的情况,简单地交替打开和关闭更新更直接:
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:
(function() {
var switcher;
function count() {
$("div").html(1 + parseInt($("div").html(), 10));
}
$(function() {
switcher = setInterval(count, 1000);
$("input").toggle(function() {
clearInterval(switcher);
$("div").toggle(); },
function() {
switcher = setInterval(count, 1000);
$("div").toggle();
});
});
}());
这篇关于jQuery:当 div 变得可见时,如何为它绑定一个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!