[英]Javascript sticky div after scroll
這個問題對許多人來說可能是愚蠢的。 我在純JS中滾動后制作粘性div。 有些人可能建議在jQuery中使用它,但我對它不感興趣。 我需要的是類似的東西這個 。 div在這里一直移動到頂部,但我需要它有60px頂部。 我制作了一個劇本,但它不起作用。 誰能幫我解決這個問題?
這是我的代碼。
HTML
<div id="left"></div>
<div id="right"></div>
CSS
#left{
float:left;
width:100px;
height:200px;
background:yellow;
}
#right{
float:right;
width:100px;
height:1000px;
background:red;
margin-top:200px;
}
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';
}
}
這就是我需要實現的目標。 左邊的div必須有margin-top:200px
和position:absolute
on page load。 當用戶滾動頁面時,左側div應該滾動,當它到達top:60px;
它的位置和保證金頂部應該改為position:fixed
和margin-top:60px;
這是FIDDLE
CSS
#left {
float:left;
width:100px;
height:200px;
background:yellow;
margin:200px 0 0;
}
#left.stick {
position:fixed;
top:0;
margin:60px 0 0
}
添加了一個棒類,所以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 = '';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.