Kis*_*ore 6 javascript scroll sticky
这个问题对许多人来说可能是愚蠢的.我在纯JS中滚动后制作粘性div.有些人可能建议在jQuery中使用它,但我对它不感兴趣.我需要的是类似的东西这个.div在这里一直移动到顶部,但我需要它有60px顶部.我制作了一个剧本,但它不起作用.谁能帮我解决这个问题?
这是我的代码.
HTML
<div id="left"></div>
<div id="right"></div>
Run Code Online (Sandbox Code Playgroud)
CSS
#left{
float:left;
width:100px;
height:200px;
background:yellow;
}
#right{
float:right;
width:100px;
height:1000px;
background:red;
margin-top:200px;
}
Run Code Online (Sandbox Code Playgroud)
JS
window.onscroll = function()
{
var left = document.getElementById("left");
if (left.scrollTop < 60 || self.pageYOffset < 60) {
left.style.position = 'fixed';
left.style.top = '60px';
} else if (left.scrollTop > 60 || self.pageYOffset > 60) {
left.style.position = 'absolute';
left.style.margin-top = '200px';
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我需要实现的目标.左侧div必须具有margin-top:200px和position:absolute页面加载.当用户滚动页面时,左侧div应滚动,当它到达top:60px;其位置时,margin-top应更改为position:fixed和margin-top:60px;
这是FIDDLE
Jay*_*ris 17
CSS
#left {
float:left;
width:100px;
height:200px;
background:yellow;
margin:200px 0 0;
}
#left.stick {
position:fixed;
top:0;
margin:60px 0 0
}
Run Code Online (Sandbox Code Playgroud)
添加了一个棒类,所以javascript不必做太多的工作.
JS
// set everything outside the onscroll event (less work per scroll)
var left = document.getElementById("left"),
// -60 so it won't be jumpy
stop = left.offsetTop - 60,
docBody = document.documentElement || document.body.parentNode || document.body,
hasOffset = window.pageYOffset !== undefined,
scrollTop;
window.onscroll = function (e) {
// cross-browser compatible scrollTop.
scrollTop = hasOffset ? window.pageYOffset : docBody.scrollTop;
// if user scrolls to 60px from the top of the left div
if (scrollTop >= stop) {
// stick the div
left.className = 'stick';
} else {
// release the div
left.className = '';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21948 次 |
| 最近记录: |