js固定导航

JavaScript011

js固定导航,第1张

<script type="text/javascript">

function htmlScroll() {

var top = document.body.scrollTop || document.documentElement.scrollTop

if (elFix.data_top <top)

{

elFix.style.position = 'fixed'

elFix.style.top = 0

elFix.style.left = elFix.data_left

}

else

{

elFix.style.position = 'static'

}

}

function htmlPosition(obj)

{

var o = obj

var t = o.offsetTop

var l = o.offsetLeft

while (o = o.offsetParent)

{

t += o.offsetTop

l += o.offsetLeft

}

obj.data_top = t

obj.data_left = l

}

var oldHtmlWidth = document.documentElement.offsetWidth

window.onresize = function() {

var newHtmlWidth = document.documentElement.offsetWidth

if (oldHtmlWidth == newHtmlWidth)

{

return

}

oldHtmlWidth = newHtmlWidth

elFix.style.position = 'static'

htmlPosition(elFix)

htmlScroll()

}

window.onscroll = htmlScroll

var elFix = document.getElementById('fixedRight')

htmlPosition(elFix)

</script>

使元素固定在网页中,不需要用到JS的,只需要用到CSS样式就可以了。

使用css 中的   position:fixed fixed是相对于浏览器的定位,设置了这个样式的元素将不会随页面滚动而改变位置,固定在屏幕中。

如 :

.classname {

position:fixed

left:0

top:0

z-index:9999

}

window.onscroll = function() {

var topH = document.documentElement.scrollTop || document.body.scrollTop//获取距离页面顶部的距离

var ele = document.getElementById("top")//你的导航栏id

if( topH >= 80 ) {//当距离顶部超过XXX

             //换logo的代码

} else {

    //恢复第一个logo的代码

}

导航栏的css用定位悬浮即可