時候,我們會希望網頁自動跳轉,應用場景包括:
下面總結下如何在前端頁面中控制跳轉的方法:
利用html的refresh
<meta http-equiv="refresh" content="0;url=index.html">
其中0表示0秒以后跳轉,可以自行設定時間。
利用js的href屬性
window.location.href='index.html';
如果要設定延遲時間,則加上setTimeout
setTimeout("javascript:location.href='index.html'", 5000);
利用js的navigate方式
window.navigate("index.html");
自動刷新頁面
在上述方式中,如果跳轉的頁面就是本頁面,那么就是自動刷新頁面的功能。
或者使用reload
location.reload()
跳轉到上一頁,下一頁的方式
window.history.go(-1);
其中 -1 表示上一頁,如果沒有負號的就是表示下一頁
如果不是1而是 2,3,4......n 則表示前進或者后退 n 頁
后退還可以用
window.history.back();
兩者的區別是:
go(-1):返回上一頁,原頁面表單中的內容會丟失;
back():返回上一頁,原頁表表單中的內容會保留。
前進則對應的是:
history.forward():
此外,還有一個參數 history.length 記錄了頁面前進的序號,如果等于0表示第一頁
怎么選擇
至此,自動跳轉頁面、刷新頁面、前后切換的方法都齊了!方法多了就有了選擇恐懼癥?
基本原則:
單純的頁面跳轉建議就用html的refresh方法,無需js代碼,很簡潔。
如果比較復雜,涉及js代碼的業務功能,再加上跳轉功能的,就用js的各種方法。
此外還要考慮頁面是否刷新的問題,希望刷新就用go,否則用back/forward
久都沒有去慕課網學習學習了,剛恰好就看見了一個用的比較多的小例子——頁面回到頂部,記得之前自己也是在初學web時,被這個坑了一回,因此今天特地拿來分享分享……
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>頁面回到頂部</title> <link rel="stylesheet" type="text/css" href="mycss.css"> <script type="text/javascript" src="myjs.js"></script> </head> <body> <a href="javascript:;" id="btn" title="回到頂部"></a> <div class="bg"> <img src="images/tb_bg.jpg" alt="" /> </div> </body> </html>
其中需要引入自己寫的一個樣式文件和一個js文件:
#btn { width: 40px; height: 40px; position: fixed; display: none; right: 65px; bottom: 10px; background: url(images/top_bg.png) no-repeat left top; } #btn:hover { background: url(images/top_bg.png) no-repeat 0 -39px; } .bg { width: 1190px; margin: 0 auto; }
js文件:
//頁面加載完畢后觸發 window.onload = function { var obtn = document.getElementById('btn'); var clientHeight=document.documentElement.clientHeight;//獲取頁面可視區域的高度 var timer = null; //存放定時器 var isTop=true; //滾動條滾動時觸發 window.onscroll=function{ var osTop = document.documentElement.scrollTop || document.body.scrollTop; if(osTop>=clientHeight){ obtn.style.display="block"; }else{ obtn.style.display="none"; } if(!isTop){ clearInterval(timer); } isTop=false; } obtn.onclick = function { timer = setInterval(function { //設置定時器 //獲取滾動條距離頂部的高度 var osTop = document.documentElement.scrollTop || document.body.scrollTop; var ispeed=osTop/5; document.documentElement.scrollTop = document.body.scrollTop =osTop-ispeed; isTop=true; if(osTop==0){ clearInterval(timer); } }, 30); } }
文件存放路徑:
基本“回到頂部”效果就這樣子實現,只是我不會在文章中添加動態效果(就是實時的添加這個動態效果圖),求大神賜教!
window.history.pushState(null, null, window.location.href);
window.addEventListener("popstate", function () {
window.history.pushState(null, null, window.location.href);
});
品同學總是會提出各種稀奇古怪的需求,比如qj用戶的返回操作。。。
上面的代碼經常被用來禁止網頁頁面的返回,經過個人的測試(Chrome/92.0.4497.0),必須在用戶有了交互之后才能生效,否則不生效;
*請認真填寫需求信息,我們會在24小時內與您取得聯系。