jQuery:如何在div可见时为div绑定一个事件? [英] jQuery: How to bind an event for the div when it becomes visible?
问题描述
我有一个div元素:
<div id="tab1">
Tab data
</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()
为返回TRUE或FALSE > :visible
:
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可见时为div绑定一个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!