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

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

我想要如下伪代码:

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

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

谢谢。


当前回答

有一个jQuery插件可以观察DOM属性的变化,

https://github.com/darcyclarke/jQuery-Watch-Plugin

你需要做的就是绑定MutationObserver

然后你可以使用它来观看div使用:

$("#selector").watch('css', function() {
    console.log("Visibility: " + this.style.display == 'none'?'hidden':'shown'));
    //or any random events
});

其他回答

我的解决方案:

; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
    var cssFn = $.fn[ name ];
    $.fn[ name ] = function( speed, easing, callback ) {
        if(speed == null || typeof speed === "boolean"){
            var ret=cssFn.apply( this, arguments )
            $.fn.triggerVisibleEvent.apply(this,arguments)
            return ret
        }else{
            var that=this
            var new_callback=function(){
                callback.call(this)
                $.fn.triggerVisibleEvent.apply(that,arguments)
            }
            var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
            return ret
        }
    };
});

$.fn.triggerVisibleEvent=function(){
    this.each(function(){
        if($(this).is(':visible')){
            $(this).trigger('visible')
            $(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
        }
    })
}
})(jQuery);

使用示例:

if(!$info_center.is(':visible')){
    $info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
    processMoreLessButton()
}

function processMoreLessButton(){
//some logic
}

有一个jQuery插件可以观察DOM属性的变化,

https://github.com/darcyclarke/jQuery-Watch-Plugin

你需要做的就是绑定MutationObserver

然后你可以使用它来观看div使用:

$("#selector").watch('css', function() {
    console.log("Visibility: " + this.style.display == 'none'?'hidden':'shown'));
    //or any random events
});

我有同样的问题,并创建了一个jQuery插件来解决我们的网站。

https://github.com/shaunbowe/jquery.visibilityChanged

下面是基于你的例子你应该如何使用它:

$('#contentDiv').visibilityChanged(function(element, visible) {
    alert("do something");
});

没有本地事件你可以挂钩到这个,但是你可以触发一个事件从你的脚本后,你已经使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');
});

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

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

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