本篇内容介绍了“如何用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
}
}
“如何用JavaScript实现楼层效果”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。