您的位置:首页 > Web前端 > JavaScript

js固定在顶部

2015-10-19 17:18 691 查看
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1" />
<title></title>
<style>
*{margin: 0px;padding: 0px;}
html{overflow: auto;position: relative;}
.div1{width: 100%;height: 3rem;background: #8A2BE2;}
.div2{width: 100%;height: 3rem;background: #D2691E;}
.div3{width: 100%;height: 4rem;background: #E5EECC;text-align: center;line-height: 4rem;}
.div4{width: 100%;height: 9rem;background: #FF0000;}
.div5{width: 100%;height: 9rem;background: #FFA500;}
</style>

</head>
<body>
<script>
var iWidth=document.documentElement.getBoundingClientRect().width;
iWidth=iWidth>540?540:iWidth;
document.getElementsByTagName("html")[0].style.fontSize=iWidth/10+"px";
</script>
<div class="wrap">
<div class="div1"></div>
<div class="div2"></div>
<div class="div3" id="fixed">固定</div>
<div class="div4"></div>
<div class="div5"></div>
</div>
</body>
<script src="js/jquery-1.11.3.js"></script>
<script>

window.onload=function(){
var fixedTop = document.getElementById('fixed').offsetTop;
document.ontouchmove = function() {
move();
}

window.onscroll=function(){
move();
}

function move(){
var t = document.documentElement.scrollTop || document.body.scrollTop;
if (t >= fixedTop) {
document.getElementById('fixed').style.position = "fixed";
document.getElementById('fixed').style.top=0;
} else {
document.getElementById('fixed').style.position = "static";
};
console.log(document.getElementById('fixed').offsetTop)
}
}
</script>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: