在html中如何实现跟随页面滚动的DIV层?(具体实现步骤)

在html中如何实现跟随页面滚动的DIV层?(具体实现步骤),第1张

这是右边的浮动导航,像新浪微博这个这样的

body{_background-image:none     /*հҳΪ*/_background-attachment:fixed }//这个是针对ie6的

.navi{left:51% margin-left:474pxtop:120pxposition:fixed_position: absolute_top: expression(documentElement.scrollTop + 120 + "px") z-index:99}

.navi a{background-image: url(背景地址) background-repeat:no-repeatdisplay: block  width:119px}

.navi a1{background-position: 0px 0px  height:30px}

.navi a2{background-position: 0px -30px  height:30px}

<div class="navi" id="navi">

<a href="" class="a1" ></a>

<a href="" class="a2"></a>

<script type='text/javascript'>

(function(){

var nav= document.getElementById('navi')

var fnav= function(){

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

 if(top>500){

  nav.style.display = 'block'

  nav.style.marginTop="0px"

 }else{

 nav.style.marginTop="500"-top+"px"

}

}

window.onload =window.onscroll = fnav

})()

</script>

</div>

完全用CSS控制就可以了,页面在滚动,给这个DIV设置position:fixed那么页面不管怎么滚动,这个DIV是中在顶端

解决方案二:

显示合作div absolute定位,判断滚动到div位置的时候设置position为fixed,同时设置top为0

<div style="height:500pxbackground:#999"></div>

<div id="fixedMenu" style="background:#eeewidth:100%">我是菜单,我到页头会固定</div>

<div style="height:900pxbackground:#999"></div>

<script type="text/javascript" src="http://www.coding123.net/js/jquery.js"></script>

<script type="text/javascript">

$(function () {

var ie6 = /msie 6/i.test(navigator.userAgent)

, dv = $('#fixedMenu'), st

dv.attr('otop', dv.offset().top)//存储原来的距离顶部的距离

$(window).scroll(function () {

st = Math.max(document.body.scrollTop || document.documentElement.scrollTop)

if (st >= parseInt(dv.attr('otop'))) {

if (ie6) {//IE6不支持fixed属性,所以只能靠设置position为absolute和top实现此效果

dv.css({ position: 'absolute', top: st })

}

else if (dv.css('position') != 'fixed') dv.css({ 'position': 'fixed', top: 0 })

} else if (dv.css('position') != 'static') dv.css({ 'position': 'static' })

})

})

</script>

解决方案三:

对页面y轴偏移量进行判断,如果大于某个值(具体情况具体应对),克隆原来的层,设置新的id,新的id意味着新的css样式:position:fixed,然后隐藏原来的层,添加克隆的层; 否则,即向上滑动到一定位置时,remove克隆的层,显示隐藏的层,达到目的~代码仅供参考。。。

$(window).scroll(function(){

if(window.pageYOffset>108){

if($("#topbar").length == 0){

var x=$("#wrap_most_used_bookmark").clone()

x.attr("id","topbar")

$("body").append(x)

$("#return_top").fadeIn()

}

}

else{

$("#topbar").remove()

$("#return_top").fadeOut()

}

})


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5897183.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-07
下一篇 2023-03-07

发表评论

登录后才能评论

评论列表(0条)

保存