问题
Header
$(document).ready(function() {
$('#user_box').animate({width: "263px"}, "slow");
$('#submit').click(function(){
$('#user_box').animate({width: "0px"}, "slow");
});
});
Content
<div id="user_box">
<form name="login_form" id="login_form" method="post" action="index.php">
Username:<br />
<input type="text" name="username"><br />
<input type="submit" value="Submit" id="submit" />
</form>
</div>
As you can see, I've made it do when submit is clicked, the user_box animates back to 0pxs (slides right). Problem is I need to delay the page load by about 1 second to give the animation time to finish. But only when the Submit button is clicked. How can I delay the page to allow the animation to finish?
I've tried..
$('#submit').delay(3500, function(){
window.location = toLoad;
});
with no joy. Any help would be greatly appreciated. Thank you.
p.s. The general idea is the user_box slides right with each query and return left with result. It'll be mainly PHP, hence the on page load it slide right to left. I'll wangle something later to stop it happening when logged in or something.
回答1:
The most reliable and flexible way to do this is to use the complete
callback option on the $().animate
call:
$('#btn_submit').click(function(e){
$submit = $(this);
e.preventDefault(); // prevent the form from being submitted until we say so
$('#user_box').animate(
{ width: "0px" },
{
duration: "slow",
complete: function(){ //callback when animation is complete
$submit.parents('form').submit();
}
}
);
});
Note that I've changed the id
of the submit button. You should not give form elements the name of form properties.
See the jQuery $().animate()
API for more options: http://api.jquery.com/animate/
回答2:
You probably should use AJAX for this type of thing, but if you really want to:
document.getElementById('submit').addEventListener('click', function(e) {
e.preventDefault();
setTimeout(function() {
document.getElementById('login_form').submit();
}, 3500);
}, false);
回答3:
- I think it's better to use .submit(fnc) then .click - should afaik work also upon Enter
- Use event.preventDefault() and then submit it by yourself when the animation is finished
来源:https://stackoverflow.com/questions/3741384/delay-page-change-on-submit-jquery