利用Pjax实现网页无刷新加载的详细方法

很多朋友问我网站PJAX的问题,这里一篇文章来统一解决大家的问题!

加入 Pjax 后,我们的网站可以实现无刷新加载网页,加上一个良好的过度 loading 动画,这样用户的体验度会更好一些。

0x00 引入jquery.pjax.js资源

在网站的 head 双标签内加入如下资源引入代码:

<script src="https://api.dyboy.cn/static/js/jquery.min.js" type="text/javascript"></script>
<script src="https://api.dyboy.cn/static/js/jquery.pjax.js" type="text/javascript"></script>

0x01 包裹刷新区域

自己在网页需要无刷新效果的地方,比如网站的 body 标签下的一个 <div id="wrap"></div> 包裹着网站的全部内容,那么要刷新 wrap 包裹的内容区域。

下一步,就是在</body> 标签前,添加如下的代码:

<script type="text/javascript">
$(document).pjax('a[target!=_blank]', '#wrap', {fragment: '#wrap',timeout: 8000}); //#wrap为刷新的id
    $(document).on('pjax:send', function() {
    $(".loading").css("display", "block");
    //预加载函数可写在这里
});

$(document).on('pjax:complete', function() {
    //回调函数
    if( $('pre').length ){ prettyPrint(); }        //回调函数解决文章页代码不高亮的问题
    $(".loading").css("display", "none");
    //pjax加载结束的回调函数 解决js无法定位的问题
    //重新定位容器内容的函数写在这里
});
</script>

0x02 过渡动画

在主要的样式文件,比如 main.css 文件中添加如下的 CSS 代码:

/*pjax 动画*/
.loading{display:none}
.loading{height:100%;width:100%;position:fixed;top:0;left:0;z-index:999999;background-color:rgba(250,250,250,.9)}
.loading img{width: 280px;height:210px;position: relative;top: 45%;left: 50%;margin-left:-140px;margin-top: -105px;}
#loader{display: block; position: relative; left: 50%; top: 50%; width: 150px; height: 150px; margin: -75px 0 0 -75px; border-radius: 50%; border: 3px solid transparent; border-top-color: #ff5a5a; -webkit-animation: spin 1s linear infinite; animation: spin 1s linear infinite;}
#loader:before{content: ""; position: absolute; top: 5px; left: 5px; right: 5px; bottom: 5px; border-radius: 50%; border: 3px solid transparent; border-top-color: #5af33f; -webkit-animation: spin 3s linear infinite; animation: spin 3s linear infinite;}
#loader:after{content: ""; position: absolute; top: 15px; left: 15px; right: 15px; bottom: 15px; border-radius: 50%; border: 3px solid transparent; border-top-color: #6dc9ff; -webkit-animation: spin 2s linear infinite; animation: spin 2s linear infinite;}
@-webkit-keyframes spin{0%{-webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg);} 100%{-webkit-transform: rotate(360deg); -ms-transform: rotate(360deg); transform: rotate(360deg);}}
@keyframes spin{0%{-webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg);} 100%{-webkit-transform: rotate(360deg); -ms-transform: rotate(360deg); transform: rotate(360deg);}}

Loading效果

动画效果是本博客的效果,其他的大家自己改吧,这样就OK了~

发表评论 / Comment

用心评论~

金玉良言 / Appraise
我吃小孩LV 2
2021-10-02 05:53
文件链接挂了
幻想家LV 2
2020-08-13 09:48
马克一下
她说,LV 2
2020-08-13 09:47
感谢博主的无私奉献~
星缘LV 1
2020-04-14 18:37
装上没用啊,出来具体教教啊
JimmyQinLV 1
2020-03-02 12:39
很详细,给博主赞一波。就是不知道为什么过渡动画不生效。

Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23