[英]Button in fixed position in only one div
我創建了兩個 div,一個在頂部,一個在底部。 我創建了一個按鈕。 我在左側底頁給出了一個屬性作為固定位置。 如果我滾動頁面,按鈕僅固定在該位置。 基本上按鈕在整個頁面的固定位置。 我的要求:當我滾動頁面時,按鈕應該固定在某個特定的高度。 當我滾動頁面時,按鈕應該固定在左按鈕,直到第一個 div 底線接觸按鈕底線。 然后我滾動頁面,按鈕應該隨着第一個 div 的底線移動。
基本上按鈕應該在固定位置,直到第一個 div 底線。 當第一個 div 底線與按鈕底線折疊時,按鈕應該是相對/絕對的並隨之移動。
希望你明白我的要求。 以下是我正在尋找要求的代碼
#top { border: 1px solid black; height: 900px; width: 80%; position: absolute; } .button { background-color: #4CAF50; border: none; color: white; bottom: 0px; font-size: 16px; margin-left: 0px; cursor: pointer; padding: 10px 24px; position: fixed; } #bottom { border: 1px solid black; height: 900px; width: 80%; top: 910px; position: relative; } #middle { bottom: 50px; position: fixed; }
<html> <body> <div id="top"> <div id="middle"> <button class="button">Fixed Element</button> </div> </div> <br> <br> <div id="bottom"> </div> </body> </html>
我認為僅使用css
是不可能的。 你需要javascript
或jquery
。 您需要jquery
來運行我的示例。 您應該使用top
或其他元素測量滾動量,並相應地更改按鈕的底部/頂部,如下所示:
查詢
$(window).scroll(function () {
if (($(this).scrollTop()+$(window).height())>$('#top').height()){
$("#btn_fixed").css({ bottom: ($(this).scrollTop()+$(window).height()- $('#top').height())+"px" });
}else{
$("#btn_fixed").css({ bottom: '0px' });
}
});
我已經更改了您代碼的css
和html
。
CSS
#top {
border: 1px solid black;
height: 900px;
width: 80%;
position: absolute;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
bottom: 0px;
font-size: 16px;
margin-left: 0px;
cursor: pointer;
padding: 10px 24px;
position: fixed;
}
#bottom {
border: 1px solid black;
height: 900px;
width: 80%;
top: 910px;
position: relative;
}
HTML
<div id="top">
<div id="middle">
<button class="button" id="btn_fixed">Fixed Element</button>
</div>
</div>
<br>
<br>
<div id="bottom">
</div>
使用位置:粘性; 在你的#middle
div
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.