我在我的网站上使用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”就会被提醒!

其他回答

我的解决方案:

; (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插件来解决我们的网站。

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

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

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

你也可以尝试一下jQuery插件中提到的并行线程https://stackoverflow.com/a/3535028/741782

$(函数(){ 美元(文档)。点击(函数(){ if ($('#contentDiv').is(':visible')) { 警报(“可见的”); }其他{ 警报(“隐藏”); } }); }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <div id="contentDiv">Test I'm here</div> <按钮onclick = " $ (' # contentDiv ') .toggle ();>切换div</按钮> . quot

DOM突变观察者正在解决这个问题。它们允许你将观察者(一个函数)绑定到改变dom元素的内容、文本或属性的事件上。

随着IE11的发布,所有主流浏览器都支持此功能,请访问http://caniuse.com/mutationobserver

示例代码如下:

$(函数() { $('#show').click(function() { $('#testdiv').show(); }); var observer = new MutationObserver (function(mutations) { 警报(“属性已更改! }); var target = document.querySelector('#testdiv'); observer.observe(target, { 属性:真 }); }); <div id=“testdiv” style=“display:none;”>hidden</div> <按钮 id=“显示”>显示隐藏的 div</button> <script type=“text/javascript” src=“https://code.jquery.com/jquery-1.9.1.min.js”></script>