1. 程式人生 > 程式設計 >JavaScript實現樓層效果

JavaScript實現樓層效果

本文例項為大家分享了實現樓層效果的具體程式碼,供大家參考,具體內容如下

* {
            margin: 0;
            padding: 0;
        }
        
        html,body {
            width: 100%;
            height: 100%;
        }
        
        ul {
            width: 100%;
            height: 100%;
        }
        
        ul>li {
            list-style: none;
            width: 100%;
            height: 100%;
            font-size: 100px;
            text-align: center;
        }
        
        ol {
            position: fixed;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
        }
        
        ol>li {
            list-style: none;
            width: 100px;
            line-height: 40px;
            text-align: centerpCgcTGJdzy
; border: 1px solid #000; } .selected { backgroundpCgcTGJdzy: shttp://www.cppcns.comkyblue; }
 <ul>
        <li>www.cppcns.com我是第1層</li>
        <li>我是第2層</li>
        <li>我是第3層</li>
        <li>我是第4層</li>
        <li>我是第5層</li>
    </ul>
 
    <ol>
        <li class="selected">第1層</li>
        <li>第2層</li>
        <li>第3層</li>
        <li>第4層</li>
        <li>第5層</li>
</ol>

// 1.初始化樓層的顏色
let oPages = document.querySelectorAll("ul>li");
let colorArr = ['green','blue','purple','red','yellow'];
        for (let i = 0; i < oPages.length; i++) {
            let page = oPages[i];
            page.style.background = colorArr[i];
        }
 
        // 2.實現點選誰就選中誰
        let oItems = document.querySelectorAll("ol>li");
        let currentItem = oItems[0];
 
        // 獲取可視區域的高度
        let screenHeight = getScreen().height;
 
        let timerId = null;
   www.cppcns.com
for (let i = 0; i < oItems.length; i++) { let item = oItems[i]; item.onclick = function() { currentItem.className = ""; this.className = "selected"; currentItem = this; // 實現滾動 // window.scrollTo(0,i * screenHeight); // 注意點: 通過documentElement.scrollTop來實現滾動,在設定值的時候不能新增單位 // document.documentElement.scrollTop = i * screenHeight + "px"; // document.documentElement.scrollTop = i * screenHeight; clearInterval(timerId); timerId = setInterval(function() { let begin = document.documentElement.scrollTop; let target = i * screenHeight; let step = (target - begin) * 0.2; begin += step; if (Math.abs(Math.floor(step)) <= 1) { clearInterval(timerId); document.documentElement.scrollTop = i * screenHeight; return; } document.documentElement.scrollTop = begin; },50); } } //獲取瀏覽器視口寬高 function getScreen() { let width,height; if (window.innerWidth) { width = window.innerWidth; height = window.innerHeight; } else if (document.compatMode === "BackCompat") { width = document.body.clientWidth; height = document.body.clientHeight; } else { width = document.documentElement.clientWidth; height = document.documentElement.clientHeight; } return { width: width,height: height } }

JavaScript實現樓層效果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。