jquery redirect on click or after 10 seconds

2020-04-08 11:13发布

问题:

I have a spash screen on a website that has a div with the ID of "splash" i'm trying to make the div fade in then if the user clicks on the div it fades out and redircts to the main site. If the user dosen't click it just fades out and redirects after 10 seconds.

The timed redirect is working but not the click function.

    <script type="text/javascript">
  $(document).ready(function() {
  $('#splash').hide();  
        $('#splash').fadeIn(1000, function() {
              $(this).delay(10000).fadeOut(1000, function() { 
               window.location = 'http://www.examle.com'; });
              $(this).click().fadeOut(1000,function() { 
               window.location = 'http://www.example.com'; });
         });
  });
</script>

Any help would be great

回答1:

Try this:

$(document).ready(function() {
  $('#splash').hide();
  $('#splash').click(function(){
             $(this).fadeOut(1000,function() { 
                     window.location = 'http://www.example.com'; });
             });
  $('#splash').fadeIn(1000, function() {
           window.setTimeout ( function() {
             $('#splash').fadeOut(1000, function() { 
               window.location = 'http://www.example.com'; }) }
             , 10000);
     });
 });​

Changes that I've made to the example:

I've moved setting the click handler outside the fadeOut function (better practice, IMHO) and I've changed your call to delay() to a setTimeout().

The difference is, delay() will not allow other jQuery code to be executed in the background, while setTimeout() will.