JavaScript实现楼层效果
程序员文章站
2022-06-23 13:06:40
本文实例为大家分享了javascript实现楼层效果的具体代码,供大家参考,具体内容如下* { margin: 0; padding: 0;...
本文实例为大家分享了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: center; border: 1px solid #000; } .selected { background: skyblue; }
<ul> <li>我是第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>
js:
// 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; 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 } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。