我有一个div元素:<div id="tab1"> Tab data </div>。
当这个div变得可见(获取display: block;)时,如何绑定一个自定义事件?
我还想在这个div变得不可见(获取display: none;)时绑定一个事件。
我想用jQuery来做这件事。
编辑:我正在用ajax内容制作简单的标签。我希望这个选项卡上的内容是ajax更新,只有当该选项卡是可见的。
发布于 2010-10-05 08:56:05
根据可见性启动和停止AJAX更新。对于,可以使用返回TRUE或FALSE
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);
}下面是一个简单的计时器示例,当计时器不可见时它会停止。请注意,当这些数字不可见时,它们并不会一直增加:
(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);
}
});
});
}());
当然,在上面的情况下,也许你的情况下,交替打开和关闭更新更简单:
(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();
});
});
}());发布于 2010-10-05 04:57:41
始终将事件绑定到div,但在事件内部,执行类似以下操作:
if($(self).is(":visible")){
// Implement your code
}现在,只有当元素对用户可见时,才会触发您的事件。
https://stackoverflow.com/questions/3859034
复制相似问题