Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

javascript - 当div可见时触发动作的jQuery事件(jQuery event to trigger action when a div is made visible)

I'm using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.(我在我的网站中使用jQuery,并且当某个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?(是否有可能将某种“isvisible”事件处理程序附加到任意div并且在div可见时运行某些代码?) I would like something like the following pseudocode:(我想要像下面的伪代码:) $(function() { $('#contentDiv').isvisible(function() { alert("do something"); }); }); The alert("do something") code should not fire until the contentDiv is actually made visible.(在实际使contentDiv可见之前,不应触发警报(“执行某些操作”)代码。) Thanks.(谢谢。)   ask by frankadelic translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:(您始终可以添加到原始.show()方法,这样您就不必在每次显示某些内容时触发事件,或者如果需要它来处理遗留代码:)

Jquery extension:(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]); }); } }); Usage example:(用法示例:) jQuery(function($) { $('#test') .bind('beforeShow', function() { alert('beforeShow'); }) .bind('afterShow', function() { alert('afterShow'); }) .show(1000, function() { alert('in show callback'); }) .show(); }); This effectively lets you do something beforeShow and afterShow while still executing the normal behavior of the original .show() method.(这有效地允许您在beforeShow和afterShow之前执行某些操作,同时仍然执行原始.show()方法的正常行为。) You could also create another method so you don't have to override the original .show() method.(您还可以创建另一个方法,这样就不必重写原始的.show()方法。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...