JQuery 自动隐藏5秒后的元素

有没有可能在表单加载5秒后使用 jQuery 自动隐藏网页中的元素?

基本上,我有

<div id="successMessage">Project saved successfully!</div>

我想在5秒钟之后消失。我已经研究过 jQuery UI 和隐藏效果,但是我在让它按照我想要的方式工作时遇到了一点麻烦。

<script type="text/javascript">
$(function() {
function runEffect() {


var selectedEffect = 'blind';


var options = {};


$("#successMessage").hide(selectedEffect, options, 500);
};


$("#successMessage").click(function() {
runEffect();
return false;
});
});
</script>

我希望删除 click 函数,并添加一个超时方法,该方法在5秒钟后调用 runEffect ()。

257409 次浏览
$(function() {
// setTimeout() function will be fired after page is loaded
// it will wait for 5 sec. and then will fire
// $("#successMessage").hide() function
setTimeout(function() {
$("#successMessage").hide('blind', {}, 500)
}, 5000);
});

Note: In order to make you jQuery function work inside setTimeout you should wrap it inside

function() { ... }

You use setTimeout on you runEffect function :

function runEffect() {
setTimeout(function(){
var selectedEffect = 'blind';
var options = {};
$("#successMessage").hide(selectedEffect, options, 500)
}, 5000);
}
$('#selector').delay(5000).fadeOut('slow');

I think, you could also do something like...

setTimeout(function(){
$(".message-class").trigger("click");
}, 5000);

and do your animated effects on the event-click...

$(".message-class").click(function() {
//your event-code
});

Greetings,

You can try :

setTimeout(function() {
$('#successMessage').fadeOut('fast');
}, 30000); // <-- time in milliseconds

If you used this then your div will be hide after 30 sec.I also tried this one and it worked for me.

This is how you can set the timeout after you click.

$(".selectorOnWhichEventCapture").on('click', function() {
setTimeout(function(){
$(".selector").doWhateverYouWantToDo();
}, 5000);
});

//5000 = 5sec = 5000 milisec

Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.

You can do this with 1 line of code:

$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);

If you're using jQuery you don't need setTimeout, at least not to autohide an element.

jQuery(".success_mgs").show(); setTimeout(function(){ jQuery(".success_mgs").hide();},5000);