我試圖將綠色框鎖定在用戶滾動瀏覽內容的最頂端。但是,當您滾動時,在綠色框的頂部有間隙(如演示中所示)鎖定在滾動上的元素純JavaScript否Jquery
我試圖將位置設置爲綠色框固定,但它跳出紅色框。所以它需要保持絕對。
請看例子中,我將它設置在這裏住http://jsfiddle.net/jpXjH/839/
還是看看這裏的代碼
<div style="padding: 20px 0px; background-color:cyan;">
This is a header with some random content
</div>
<div style="width:480px; height:1400px; overflow:hidden; margin:auto;
border:1px solid gray; position:relative; background-color: #ff5d5d; ">
<div id="locked">
This element needs to be on the very top LOCKED when scrolled down.
However you can see there is a gap in the very top when you scroll.
</div>
</div>
<style>
#locked{
background-color: limegreen;
padding:10px;
width:150px;
position:absolute;
top:0;
right:0;
}
</style>
<script>
window.onscroll = changePos;
function changePos() {
var locked = document.getElementById("locked");
if (window.pageYOffset > 30) {
locked.style.position = "absolute";
locked.style.float = "right";
locked.style.top = pageYOffset + "px"
} else {
locked.style.position = "";
locked.style.top = "";
}
}
<script>
在此先感謝
這是你想要實現的嗎?不知道我是否理解你的問題http://jsfiddle.net/jpXjH/843/ – wiesion
這正是它謝謝:) – mark