当div可见时触发动作的jQuery事件 [英] jQuery event to trigger action when a div is made visible

查看:127
本文介绍了当div可见时触发动作的jQuery事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.

是否可以附加某种isvisible事件处理程序到任意div并且当div被显示时运行某些代码?

Is it possible to attach some sort of "isvisible" event handler to arbitrary divs and have certain code run when they the div is made visible?

我想要类似下面的伪代码:

I would like something like the following pseudocode:

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

在实际显示contentDiv之前,不应触发警报(执行某事)代码。

The alert("do something") code should not fire until the contentDiv is actually made visible.

谢谢。

推荐答案

您可以随时添加到原始。show()方法,因此您不必每次显示某些内容时触发事件,或者您需要它使用遗留代码:

You could always add to the original .show() method so you don't have to trigger events every time you show something or if you need it to work with legacy code:

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]);
    });
  }
});



用法示例:



Usage example:

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

这有效地让你在显示和AfterShow之前做一些事情,同时仍然执行原始.show的正常行为( )方法。

This effectively lets you do something beforeShow and afterShow while still executing the normal behavior of the original .show() method.

您还可以创建另一种方法,这样就不必覆盖原始的.show()方法。

这篇关于当div可见时触发动作的jQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆