我希望在頁面上的固定位置(粘滯)顯示一個按鈕,並且應始終位於頁面上其他元素的頂部,假設我不知道該頁面上使用的結構和樣式。該解決方案只能使用Javascript(無jQuery),CSS3和HTML5。如何在頁面上的每個其他元素的頂部呈現元素而不依賴於頁面中使用的結構/樣式?
解決方案必須是動態/自適應的,即不直接依賴於頁面上使用的z-index值。
我希望在頁面上的固定位置(粘滯)顯示一個按鈕,並且應始終位於頁面上其他元素的頂部,假設我不知道該頁面上使用的結構和樣式。該解決方案只能使用Javascript(無jQuery),CSS3和HTML5。如何在頁面上的每個其他元素的頂部呈現元素而不依賴於頁面中使用的結構/樣式?
解決方案必須是動態/自適應的,即不直接依賴於頁面上使用的z-index值。
演示:http://jsfiddle.net/lotusgodkk/sf1fukm5/
CSS:
.a {
position:fixed;
right:10px; //optional
top:10px; //optional
z-index:1;
background:grey; //optional
color:#000; //optional
padding:20px; //optional
}
HTML:
<div>--Content--</div>
<div class="a">Fixed</div> //Fixed div
<div>--Content--</div>....
對於動態的z-index使用jQuery:
var highest = -999;
$("*").each(function() {
var current = parseInt($(this).css("z-index"), 10);
if (current && highest < current) highest = current;
});
$('your-element-selector').css('z-index',highest);
使用JavaScript的: How can you figure out the highest z-index in your document?
參見:How to find the highest z-index within a document no matter what tags they are?
CSS:
.fixed-button {
width: 125px;
background: #FFFFFF;
border-style: solid;
border-width: 1px;
border-radius: 3px;
padding: 5px;
margin-left: 0px;
position: fixed;
z-index: 999;
top: 70px;
}
HTML:
<button class="fixed-button"> fixed-button </button>
我希望你得到了答案。你可以在任何你需要的地方更改按鈕的位置
如果z-index大於999的固定元素(示例場景將是引導程序的固定導航欄),該怎麼辦?我正在尋找一個動態的解決方案。 – Shasak 2014-10-28 12:23:11
'position:fixed' – devqon 2014-10-28 11:33:07