JSFiddle - React, Tailwind, and code Playground
HTML
<div id="con" style="height:2000px;">
<p>我是元素p</p>
<p id="myDiv" class="pop">
我是要随屏幕滚动的DIV
</p>
<p>我是元素p</p>
</div>
CSS
*{margin:0;padding: 0;background-color:#000; }
div#con{width: 800px;margin: 0 auto;}
p{width:800px;padding:20px 0;background:#fff;margin:20px auto;text-align: center;}
.pop{background:yellow;}
.active{position: fixed;_position:absolute;background:yellow;display: block;margin: 0;top:0}
JavaScript
/*
divID = 元素id
fistTop = 元素起始位置
*/
function scrollDiv(divID, fistTop){
this.fistTop = fistTop;
this.onscroll(divID);
}
scrollDiv.prototype = {
$ : function(id){return document.getElementById(id)},
timer : "", //定时器
onscroll : function(divID){
var that = this;
window.onscroll = function(){
clearTimeout(that.timer);
that.timer = setTimeout(function(){
that.sDiv(divID)
}, 50);
}
},
sDiv : function(divID){
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if(!!window.ActiveXObject && !window.XMLHttpRequest){ //ie6
if(scrollTop >= this.fistTop){
this.$(divID).className = "active";this.$(divID).style.top = scrollTop +"px";
}else{
this.$(divID).className = "pop";
}
} else { //其它浏览器
scrollTop >= this.fistTop ? this.$(divID).className = "active" : this.$(divID).className = "pop";
}
},
getPosition : function(obj) { //获取元素的位置
var top = 0,
left = 0,
width = obj.offsetWidth,
height = obj.offsetHeight;
while(obj.offsetParent){
top += obj.offsetTop;
left += obj.offsetLeft;
obj = obj.offsetParent;
}
return {"top":top,"left":left,"width":width,"height":height};
}
}
var myDiv = new scrollDiv("myDiv",100);