How can I fade out a div using jQuery?

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

Is there any way to fadeout a div after 5 Seconds without using a setTimeOut function?

回答1:

everyone knows that in jquery 1.4 there's a delay function now, right?

$('#div').delay(5000).fadeOut(400) 

that's how you do it, without having to add any custom functions or plug-ins. it's native to jquery 1.4



回答2:

Case 1: if you want to start fadeOut after 5 seconds, use this:

jQuery.fn.delay = function(time,func){     return this.each(function(){         setTimeout(func,time);     }); }; 

Then, use it like this:

$('#div').delay(5000, function(){$(#div').fadeOut()}) 

You can't achieve this without using setTimeOut at all

Case 2: if you want the duration of fadeOut to be 5 seconds, use this:

$('#div').fadeOut(5000) 


回答3:

How about the fadeOut() function. Would look something like this:

$("#myDiv").fadeOut(5000); 


回答4:

I just had the same problem and in my opinion the marked answer doesn't actually really satisfy the question. If one specifies it like

$("#myDiv").fadeOut(5000); 

as suggsted, the fading process itself will last for 5 seconds, but not start after 5 seconds.

So I was searching for an alternative, without having to include another jQuery plugin etc. The simplest solution I came up with was to write it as follows:

$("#myDiv").fadeTo(5000,1).fadeOut(1000); 

It uses the fadeTo effect and it is somehow a "hack". I let the fadeTo run for 5 seconds and let it fade to 1 = 100% opacity. In this way the user doesn't perceive any change. Afterwards the normal call to fadeOut with a duration of the effect of 1 second.

I guess this solution is quite simple since it doesn't require any additional plugin and can be written in 1 line.

Cheers.

//EDIT:
Apparently there is now the possibility to do something like this:

$('#myDiv').delay(800).fadeOut(1000); 

Here are some more cool, useful functions.



回答5:

Not sure if you want it to take 5 seconds or start in 5 seconds.

For it to take 5 seconds: The jQuery fadeout function can be used on a div, and it will reduce the element's opacity until it is 0 and then display none the div. The speed of the fade is a parameter for the function.

http://docs.jquery.com/Effects/fadeOut#speedcallback

To start it in 5 seconds, you'll need some sort of timer that starts when the document or window is ready, or when the div is ready depending on what you want.



回答6:

// i use this pause plugin i just wrote

$.fn.pause = function(duration) {     $(this).animate({ dummy: 1 }, duration);     return this; }; 

Call it like this :

$("#mainImage").pause(5000).fadeOut(); 

Note: you don't need a callback.



回答7:

Assuming you mean 'wait five seconds and then fade out', I think you'll have to use a plugin to force the delay, eg this one



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!