我在我的网站上使用jQuery,我想在某个div可见时触发某些操作。

是否有可能附加某种“isvisible”事件处理程序到任意div,并有一定的代码运行时,他们的div是可见的?

我想要如下伪代码:

$(function() {
  $('#contentDiv').isvisible(function() {
    alert("do something");
  });
});

警报(“do something”)代码在contentDiv实际可见之前不应该触发。

谢谢。


当前回答

你可以使用jQuery的Live Query插件。 并编写如下代码:

$('#contentDiv:visible').livequery(function() {
    alert("do something");
});

然后每当contentDiv可见时,“do something”就会被提醒!

其他回答

你可以使用jQuery的Live Query插件。 并编写如下代码:

$('#contentDiv:visible').livequery(function() {
    alert("do something");
});

然后每当contentDiv可见时,“do something”就会被提醒!

使用jQuery Waypoints:

$('#contentDiv').waypoint(function() {
   alert('do something');
});

jQuery Waypoints网站上的其他例子。

$( window ).scroll(function(e,i) {
    win_top = $( window ).scrollTop();
    win_bottom = $( window ).height() + win_top;
    //console.log( win_top,win_bottom );
    $('.onvisible').each(function()
    {
        t = $(this).offset().top;
        b = t + $(this).height();
        if( t > win_top && b < win_bottom )
            alert("do something");
    });
});

如果您想在所有实际可见的元素(和子元素)上触发事件,则使用$。show, toggle, toggleClass, addClass,或removeClass:

$.each(["show", "toggle", "toggleClass", "addClass", "removeClass"], function(){
    var _oldFn = $.fn[this];
    $.fn[this] = function(){
        var hidden = this.find(":hidden").add(this.filter(":hidden"));
        var result = _oldFn.apply(this, arguments);
        hidden.filter(":visible").each(function(){
            $(this).triggerHandler("show"); //No bubbling
        });
        return result;
    }
});

现在是元素:

$("#myLazyUl").bind("show", function(){
    alert(this);
});

你可以通过将额外的jQuery函数添加到顶部的数组(如“attr”)来添加覆盖。

没有本地事件你可以挂钩到这个,但是你可以触发一个事件从你的脚本后,你已经使div可见使用.trigger函数

e.g

//declare event to run when div is visible
function isVisible(){
   //do something

}

//hookup the event
$('#someDivId').bind('isVisible', isVisible);

//show div and trigger custom event in callback when div is visible
$('#someDivId').show('slow', function(){
    $(this).trigger('isVisible');
});