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

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

我想要如下伪代码:

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

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

谢谢。


当前回答

只需将触发器与选择器绑定,并将代码放入触发器事件中:

jQuery(function() {
  jQuery("#contentDiv:hidden").show().trigger('show');

  jQuery('#contentDiv').on('show', function() {
    console.log('#contentDiv is now visible');
    // your code here
  });
});

其他回答

$(函数(){ 美元(文档)。点击(函数(){ 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

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

在这里帮助我的是最近的ResizeObserver规格polyfill:

const divEl = $('#section60');

const ro = new ResizeObserver(() => {
    if (divEl.is(':visible')) {
        console.log("it's visible now!");
    }
});
ro.observe(divEl[0]);

注意,它是跨浏览器和性能的(没有轮询)。

下面的代码(来自http://maximeparmentier.com/2012/11/06/bind-show-hide-events-with-jquery/)将使您能够使用$('#someDiv')。(“秀”,someFunc);。

(function ($) {
  $.each(['show', 'hide'], function (i, ev) {
    var el = $.fn[ev];
    $.fn[ev] = function () {
      this.trigger(ev);
      return el.apply(this, arguments);
    };
  });
})(jQuery);