js實現滾動內容切換tab

1.html代碼css

<header></header>
<ul class="nav">
    <li class="item active">1</li>
    <li class="item">2</li>
    <li class="item">3</li>
</ul>
<div class="container">
    <section>1</section>
    <section>2</section>
    <section>3</section>
</div>html


2.css代碼htm

* {
    padding: 0;
    margin: 0;
}
header {
    height: 150px;
}
.nav {
    height: 50px;
    width: 100%;
    background-color: #eee;
}
.item {
    width: 150px;
    height: 49px;
    float: left;
    list-style: none;
    text-align: center;
    line-height: 50px;
    transition: background 1s;
}
.active {
    border-top: 1px solid green;
    background-color: #4179f7;
    color: #fff;
}
.fixed {
    position: fixed;
    top: 0;
}
section {
    width: 100%;
}
section:nth-child(1) {
    height: 600px;
    background-color: red;
}
section:nth-child(2) {
    height: 700px;
    background-color: green;
}
section:nth-child(3) {
    height: 700px;
    background-color: blue;
}事件

3.js代碼get

var newPos = undefined
var myReq = undefined
var nav = document.querySelector('.nav')
var navTop = nav.offsetTopit

var navList = document.getElementsByTagName('li')
var list = document.getElementsByTagName('section')io

//滾動事件function

window.addEventListener('scroll', function() {
    var scrollTop = document.documentElement.scrollTop
    if (scrollTop >= navTop) {
        if (nav.className.indexOf('fixed') === -1) {
            nav.className += ' fixed'
        }
    } else {
        nav.className = 'nav'
    }class

    Array.from(list).forEach(function(item, index) {
        navList[index].className = 'item'
        if (scrollTop >= item.offsetTop && scrollTop < item.offsetTop + item.clientHeight) {
            navList[index].className += ' active'
        }
        if (scrollTop <= list[0].offsetTop) {
            navList[0].className += ' active'
        }
    })
})cli

//點擊tab項跳轉到相應內容

Array.from(navList).forEach(function(item, index) {
    item.addEventListener('click', function() {
        Array.from(navList).forEach(function(liItem) {
            liItem.className = 'item'
        })
        item.className += ' active'
        newPos = list[index].offsetTop
        window.cancelAnimationFrame(myReq)
        move()
    })
})

function move() {     if (Math.abs(document.documentElement.scrollTop - newPos) < 20) {         document.documentElement.scrollTop = newPos         return     }     if (document.documentElement.scrollTop > newPos) {         document.documentElement.scrollTop -= 20     } else {         document.documentElement.scrollTop += 20     }     myReq = requestAnimationFrame(move) }  

相關文章
相關標籤/搜索