<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {margin: 0;padding: 0}
body {height: 2000px}
#inner {width: 100%;height: 50px;background: red;position: absolute;left: 0;top: 0}
</style>
</head>
<body>
<div id="inner">
</div>
<script type="text/javascript">
var obj11 = document.getElementById("inner");
var top11 = getTop(obj11); //div的offsetTop
var isIE6 = /msie 6/i.test(navigator.userAgent);
window.onscroll = function(){
var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (bodyScrollTop > top11){ //滚动距离 > div的offsetTop
obj11.style.position = (isIE6) ? "absolute" : "fixed";
obj11.style.top = (isIE6) ? bodyScrollTop + "px" : "0px";
} else {
obj11.style.position = "static";
}
}
function getTop(e){
var offset = e.offsetTop;
if(e.offsetParent != null) offset += getTop(e.offsetParent);
return offset;
}
</script>
</body>
</html>
js实现顶部固定,摆脱ie的抖动
最新推荐文章于 2026-06-15 09:30:08 发布
本文介绍了一种通过JavaScript监听窗口滚动事件,动态调整页面元素位置以实现平滑滚动效果的技术,包括如何使用offsetTop获取元素偏移量并根据滚动位置调整元素样式。
1883

被折叠的 条评论
为什么被折叠?



