【问题标题】:Increment z-index for each div为每个 div 增加 z-index
【发布时间】:2014-10-23 01:09:23
【问题描述】:

我正在设计一个 div 相互重叠的设计,我会为每个类的成员单独增加 z-index 1。而且我觉得jquery 有更好的方法。

我想要的是类似于 section 类的每个 div 的 z-index 比前一个大但不会被不属于特定类成员的 div 丢弃,例如

<div class="section" style="z-index:1">Lorem</div>
<div class="section" style="z-index:2">Lorem</div>
<div id="OutOfPlaceDiv">Foo</div>
<div class="section" style="z-index:3">Lorem</div>

【问题讨论】:

  • $('.section').each(function(index, el) { $(el).css('z-index', index + starting_z-index_value); });starting_z-index_value 替换为您想要开始的值。

标签: jquery html css z-index


【解决方案1】:

使用each 方法遍历具有该类的元素。

$('.section').each(function(index) {
  $(this).css("z-index", index);
});

这会将索引设置为0, 1, 2 等。如果您想从0 以外的其他内容开始:

var offset = 1;
$('.section').each(function(index) {
  $(this).css("z-index", offset + index);
});

【讨论】:

  • 对我来说工作得很好。控制台有错误吗?
  • 你有 jquery 吗?看我的回答。
  • 啊,没关系,我看错了副本……效果很好。
【解决方案2】:

一个肮脏的 css hack,但如果你只有十几个 div,那么简单而有效:

.section:nth-child(1) { z-index: 1; }
.section:nth-child(2) { z-index: 2; }
.section:nth-child(3) { z-index: 3; }
...

【讨论】:

    猜你喜欢
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多