滾動條下滑必定高度時,固定指定 ID 的導航條。javascript
使用方法:
一、修改 FixTop() 中 id 爲須要固定導航的相應 id ;html
效果:java
當滾動條下滑滾動超過導航欄位置時,導航欄固定 (移除原有,添加「position:fixed」屬性並添加 「fixtop」 類名);code
當滾動條上滑高度低於原來導航高度時,導航欄變成默認效果(移除原有,添加「position:static」屬性並添加 「fixnone」類名)。htm
function FixTop(obj) { var obj = document.getElementById(obj); var objOffset = obj.offsetTop; //console.log("對象高度"+ objOffset); window.onscroll = function() { var bodyScrollOffset = document.body.scrollTop; //console.log('往下滾動距離高度'+ bodyScrollOffset); var Result = objOffset - bodyScrollOffset; //console.log("對象減去滾動高度"+ Result); if (Result < 0 && bodyScrollOffset > objOffset) { obj.style.position = "fixed"; obj.style.top = 0; obj.setAttribute('class', 'fixtop'); } else { obj.style.position = 'static'; obj.setAttribute('class', 'fixnone'); } } } FixTop('ID');//此處填入被固定對象的ID
效果示例:效果戳我。對象