首页 » 收集 » 正文内容
利用Pjax实现网页无刷新加载的详细方法
寻梦xunm| 401| 收集
1年前
超过717天 温馨提示
本文最后更新于2022年10月04日,已超过717天没有更新,若内容或图片失效,请留言反馈。

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

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

<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery.pjax.js" type="text/javascript"></script>

0x01 包裹刷新区域

自己在网页需要无刷新效果的地方,比如网站的 body 标签下的一个

包裹着网站的全部内容,那么要刷新 wrap 包裹的内容区域。

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

<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() {
    //回调函数
    $("img[src$=jpg],img[src$=jpeg],img[src$=png],img[src$=gif]").parent("a[class!=noview]").addClass("swipebox");
    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);}}

利用Pjax实现网页无刷新加载的详细方法
动画效果是作者博客的效果,其他的大家自己改吧,这样就OK了~

0 赞 or 打赏
喜欢就打赏一点
微信 支付宝
隐私
Q Q:1340326824
邮箱:vipshiyi@qq.com
QQ群:422720328

我的音乐

微博客-专为自己编写开发的源码