先解释下:页面级指的是,楼层滚动是在整个body中滚动,div内的楼层指的是,在某个容器,如div、ul内滚动,区别在于,一个是获取document的滚动距离,监听滚动也是监听window的滚动事件,容器内滚动,获取的是子元素相对于父容器的偏移量,监听滚动也是这个容器的滚动事件:
页面级的楼层代码如下:
html代码:
<body> <!-- 导航条 --> <ul class="floor-nav"> <li class="active">楼层1</li> <li>楼层2</li> <li>楼层3</li> <li>楼层4</li> <li>楼层5</li> </ul> <!-- 滚动内容 --> <div class="foor-conent"> <div class="course">新上好课</div> <div class="learn">进站必学</div> <div class="path">学习路线</div> <div class="special">慕课专栏</div> <div class="group">限时拼团</div> </div> </body>
js代码:
var contents = document.querySelectorAll('.foor-conent div') var floors = document.querySelectorAll('.floor-nav li') var arr = [] for (i = 0; i < contents.length; i++) { arr.push(contents[i].offsetTop) } for (j = 0; j < floors.length; j++) { floors[j].index = j; floors[j].onclick = function() { window.scrollTo({ top: arr[this.index], behavior: 'smooth' }) } } window.onscroll = function() { var h = document.documentElement.scrollTop || document.body.scrollTop var index = 0 for (var i = 0; i < arr.length; i++) { if (h > arr[i]) { index = i } else { break; } } for (var j = 0; j < floors.length; j++) { // active 为高亮当前楼层导航的class样式 floors[j].classList.remove('active') } floors[index].classList.add('active') }
某个容器内的楼层代码如下:
html代码:
<body> <!-- 导航条 --> <ul class="floor-nav"> <li class="active">楼层1</li> <li>楼层2</li> <li>楼层3</li> <li>楼层4</li> <li>楼层5</li> </ul> <!-- 滚动内容,滚动的是content-wrap --> <div class="content-wrap"> <div class="foor-conent"> <div class="course">新上好课</div> <div class="learn">进站必学</div> <div class="path">学习路线</div> <div class="special">慕课专栏</div> <div class="group">限时拼团</div> </div> </div> </body>
js代码:
var wraps = document.querySelector('.content-wrap') var contents = document.querySelectorAll('.foor-conent div') var floors = document.querySelectorAll('.floor-nav li') var arr = [] for (i = 0; i < contents.length; i++) { arr.push(contents[i].offsetTop) } for (j = 0; j < floors.length; j++) { floors[j].index = j; floors[j].onclick = function() { // 这里和页面级的不同,监听的是滚动的div wraps.scrollTo({ top: arr[this.index], behavior: 'smooth' }) } } // 这里和页面级的不同,监听事件触发的主体为div wraps.onscroll = function(e) { var h = e.target.scrollTop var index = 0 for (var i = 0; i < arr.length; i++) { if (h > arr[i]) { index = i } else { break; } } for (var j = 0; j < floors.length; j++) { // active 为高亮当前楼层导航的class样式 floors[j].classList.remove('active') } floors[index].classList.add('active') }