2014-10-28 50 views
-1

我希望在頁面上的固定位置(粘滯)顯示一個按鈕,並且應始終位於頁面上其他元素的頂部,假設我不知道該頁面上使用的結構和樣式。該解決方案只能使用Javascript(無jQuery),CSS3和HTML5。如何在頁面上的每個其他元素的頂部呈現元素而不依賴於頁面中使用的結構/樣式?

解決方案必須是動態/自適應的,即不直接依賴於頁面上使用的z-index值。

+0

'position:fixed' – devqon 2014-10-28 11:33:07

回答

2

演示: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?

+0

我認爲如果z-index大於1的另一個固定元素將不起作用。這種情況的例子是bootstrap的固定導航欄 – Shasak 2014-10-28 12:20:44

+0

您可以隨時更改z-index。我僅用於演示目的。您可以將其設置爲高於頁面中的最大z-索引。這一切都取決於你的設計 – 2014-10-28 12:21:22

+0

我正在尋找一個動態的解決方案。它不應該直接取決於頁面上使用的樣式。它應該適應。 – Shasak 2014-10-28 12:24:07

0

JSFIDDLE

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> 

我希望你得到了答案。你可以在任何你需要的地方更改按鈕的位置

+0

如果z-index大於999的固定元素(示例場景將是引導程序的固定導航欄),該怎麼辦?我正在尋找一個動態的解決方案。 – Shasak 2014-10-28 12:23:11

相關問題