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

查看:32
本文介绍了当 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.

是否可以将某种可见"事件处理程序附加到任意 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?

我想要如下伪代码:

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

用法示例:

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

这有效地让您在执行 beforeShow 和 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天全站免登陆