如何在不依赖于页面中使用的结构/样式的情况下,在页面上的其他元素之上呈现一个元素

How to render an element on top of every other element on page without depending on the structure/styles used in the page?

本文关键字:元素 其他 一个 样式 依赖于 情况下 结构      更新时间:2023-09-26

我希望在页面上的固定位置(粘性)显示一个按钮,并且它应该始终位于页面上其他元素的顶部,假设我不知道该页面上使用的结构和样式。该解决方案只能使用Javascript(没有jQuery)、CSS3和HTML5。

解决方案必须是动态/自适应的,即不直接依赖于页面上使用的z索引值

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

对于使用jQuery的动态z索引:

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:如何计算文档中的最高z索引?

参考:如何在文档中找到最高的z索引,无论它们是什么标签?

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>

我希望你得到答案。您可以在需要的地方更改按钮的位置