css 固定顶部 怎么用css定义一个固定在页面

html-css04

css 固定顶部 怎么用css定义一个固定在页面,第1张

建议使用css实现,效果更佳,使用position: fixed,固定定位,具体位置的调整是用top、left、right、bottom也可以使用margin调整

css实现代码

<div style="position: fixedtop:100pxleft: autoright: auto bottom: auto" ></div>

一般的网站的浮动广告以及浮动菜单等可以使用fixed来实现,js的话需要计算位置以及滚动条滚动时触发事件从而进行计算使用window.onscroll事件代码如下

HTML部分代码

<div style="position:absolutebackground-color:redwidth: 50pxheight: 50px" id="box"></div>

Javascript部分代码

window.onscroll=function(){

var box= document.getElementById("box")

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

box.style.top=t+"px"

}

window.onscroll=function(){

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

if(autoheight>76){

$("#index-left").css("position","fixed")

$("#index-left").css("top",0)

$("#index-left").css("left",0)

}

else{

$("#index-left").css("position","absolute")

}

}你那个有兼容 我这个是我线上使用的