在html中,寫一個id為type的div:
<div class="type" id="type"></div>
css:
.type{ height: 600px; overflow-y: auto; }
當里面的內容超過高度時,div會出現滾動條,監聽這個div的滾動事件:
//監聽這個dom的scroll事件 document.getElementById("type").addEventListener("scroll", handleScroll);
在 handleScroll 函式中,獲取這個div的滾動距離,并將其保存到cookie(setCookie函式看上一篇博文):
function handleScroll() { //獲取dom滾動距離 const scrollTop = document.getElementById("type").scrollTop; console.log("scrollTop ", scrollTop); //將滾動距離保存到cookie setCookie("scrollTop", scrollTop); //console.log("getCookie", getCookie("scrollTop")); }
要想在頁面一打開就讓這個div自動滾動到上次滾動的位置,要這樣寫(getCookie函式看上一篇博文):
$(function() { const scrollTop = getCookie("scrollTop") != null ? Number(getCookie("scrollTop")):0; console.log("讀取",scrollTop); document.getElementById("type").scrollTop = scrollTop; //監聽這個dom的scroll事件 document.getElementById("type").addEventListener("scroll", handleScroll); });
這樣只要div有滾動,再重繪該頁面就能讓其自動滾動到上次滾動的位置了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/440442.html
標籤:其他
