div가 표시 될 때 작업을 트리거하는 jQuery 이벤트 의사 코드와 같은 것을 원합니다. $(function()

내 사이트에서 jQuery를 사용하고 있으며 특정 div가 표시되면 특정 작업을 트리거하고 싶습니다.

임의의 div에 일종의 “보이지 않는”이벤트 핸들러를 첨부하고 div가 표시 될 때 특정 코드를 실행할 수 있습니까?

다음 의사 코드와 같은 것을 원합니다.

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

contentDiv가 실제로 표시 될 때까지 alert ( “do something”) 코드가 실행되지 않아야합니다.

감사.



답변

항상 원본 .show () 메서드에 추가 할 수 있으므로 무언가를 표시 할 때마다 또는 레거시 코드로 작업해야하는 경우 이벤트를 트리거 할 필요가 없습니다.

jquery 확장명 :

jQuery(function($) {

  var _oldShow = $.fn.show;

  $.fn.show = function(speed, oldCallback) {
    return $(this).each(function() {
      var obj         = $(this),
          newCallback = function() {
            if ($.isFunction(oldCallback)) {
              oldCallback.apply(obj);
            }
            obj.trigger('afterShow');
          };

      // you can trigger a before show if you want
      obj.trigger('beforeShow');

      // now use the old function to show the element passing the new callback
      _oldShow.apply(obj, [speed, newCallback]);
    });
  }
});

사용 예 :

jQuery(function($) {
  $('#test')
    .bind('beforeShow', function() {
      alert('beforeShow');
    })
    .bind('afterShow', function() {
      alert('afterShow');
    })
    .show(1000, function() {
      alert('in show callback');
    })
    .show();
});

이렇게하면 원래 .show () 메서드의 정상적인 동작을 계속 실행하면서 beforeShow 및 afterShow를 효과적으로 수행 할 수 있습니다.

원래 .show () 메서드를 재정의 할 필요가 없도록 다른 메서드를 만들 수도 있습니다.


답변

이 문제는 DOM 돌연변이 관찰자들에 의해 해결되고있다 . 이를 통해 관찰자 (함수)를 컨텐츠, 텍스트 또는 dom 요소의 속성 변경 이벤트에 바인딩 할 수 있습니다.

IE11 릴리스에서는 모든 주요 브라우저가이 기능을 지원합니다. http://caniuse.com/mutationobserver를 확인하십시오 .

예제 코드는 다음과 같습니다.

$(function() {
  $('#show').click(function() {
    $('#testdiv').show();
  });

  var observer = new MutationObserver(function(mutations) {
    alert('Attributes changed!');
  });
  var target = document.querySelector('#testdiv');
  observer.observe(target, {
    attributes: true
  });

});
<div id="testdiv" style="display:none;">hidden</div>
<button id="show">Show hidden div</button>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

답변

이를 위해 연결할 수있는 기본 이벤트는 없지만를 사용하여 div를 표시 한 후 스크립트에서 이벤트를 트리거 할 수 있습니다. 트리거 기능

예 :

//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가 표시 될 때마다 “뭔가하세요”라는 경고가 나타납니다!


답변

redsquare의 솔루션 이 정답입니다.

그러나로 IN-이론 솔루션 당신은에 의해 분류 요소를 선택하는 기능을 쓸 수 있습니다 .visibilityCheck( 모든 눈에 보이는 요소 )과 확인 visibility속성 값을; 그렇다면 true뭔가를하십시오.

그 후 기능을 사용하여 setInterval()기능을 주기적으로 수행해야합니다 . clearInterval()성공적인 콜 아웃을 사용하여 타이머를 중지 할 수 있습니다 .

예를 들면 다음과 같습니다.

function foo() {
    $('.visibilityCheck').each(function() {
        if ($(this).is(':visible')){
            // do something
        }
    });
}

window.setInterval(foo, 100);

또한 일부 성능 향상을 수행 할 수 있지만 솔루션은 기본적으로 작동하지 않습니다. 그래서…


답변

다음 코드 ( http://maximeparmentier.com/2012/11/06/bind-show-hide-events-with-jquery/ 에서 추출 )를 사용하면을 사용할 수 있습니다 $('#someDiv').on('show', someFunc);.

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

답변

$ .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);
});

상단의 배열에 “attr”과 같은 추가하여 jQuery 함수에 재정의를 추가 할 수 있습니다.