当浏览器移动到不同页面时显示加载图形

时间:2015-11-18 00:03:12

标签: javascript jquery html css

我想在用户加载页面时显示加载gif。当它像这样加载时我这样做:

CSS:

.no-js #loader { display: none;  }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url(https://i.imgur.com/Bpa5eIP.gif) center no-repeat #fff;
}

JavaScript的:

<script>
$(window).load(function() {
     Animate loader off screen
    $(".se-pre-con").fadeOut("slow");;
});
</script>

HTML:

<div class="se-pre-con"></div>

我可以通过将.onClick添加到页面上的每个链接来实现这一点,但这需要时间,我想知道是否有更简单的方法在加载远离页面时显示gif。

2 个答案:

答案 0 :(得分:4)

观看unload事件或beforeunload事件,就像加载一样!

例如:

$(window).on("unload",function() {
     //your animation here
});

此外,您可以添加延迟或其他内容,以便动画在离开页面之前结束:

var triggered = false;    
$(window).on("unload",function(event) {
    if (triggered === true) {
        return; //this is run automatically after the timeout
    }

    event.preventDefault();
    // your animation here

    triggered = true; // set flag
    setTimeout(function(){$(this).trigger('unload');},1000); //set animation length as timeout
 });

我将此问题用于我的解决方案:How to trigger an event after using event.preventDefault()

答案 1 :(得分:0)

尝试使用此

$(document).ajaxStart(function() {

  $("#loading").show();
});

$(document).ajaxComplete(function() {
$("#loading").hide();
});
});

CSS

.wait {
  top: 100px;
  z-index: 2000;
  height: 100%;
  width: 100%;
  vertical-align: bottom;
  position: relative;
}
.loader {
  background-position: center center;
  z-index: 1000;
  height: auto;
  width: 100%;
  position: absolute;
}
.loaderimg {
  height: 100%;
  width: 100%;
}

HTML

<div id="loading" class="loader">
  <h2 class="text-center wait">Loading results, please be patient</h2>
  <img class="loaderimg" src="img/scr_01.gif" />
</div>