奇怪的“nth-of-type”行为

时间:2017-08-23 12:33:57

标签: javascript html css

这是使用< ul>的表格式布局的另一种方法和< li>。

每个< ul>是一行,每个< li>是一个细胞。 第1< ul>是一个标题行,所以它有一个特殊的样式,工作正常。 对于每列的宽度,我想添加“个人样式”,使用“nth-of-child”而不是class的优势。

以下是HTML和CSS内容:

var D, T, R;

function I() {
  D = document.getElementById("D");
  R = document.getElementById("R");

  // To keep 1st row always visible.
  D.onscroll = function() {
    R.style.top = D.scrollTop + "px";
  }

  // This is just arbitrary content
  var k = ["Va", "Vb"];
  for (var i = 0; i < 500; i++) {
    var e = document.createElement("ul");
    D.appendChild(e);
    for (var j = 0; j < 3; j++) {
      var d = document.createElement("li");
      e.appendChild(d);
      d.innerHTML = (!j) ? i : k[j - 1];
    }
  }
}
I();
#D {
  position: absolute;
  left: 250px;
  right: 50px;
  top: 50px;
  bottom: 50px;
  background-color: #ff8;
  overflow: auto;
  white-space: nowrap;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

ul li {
  display: table-cell;
}

ul:nth-child(odd) {
  background: #eee;
}

ul:nth-child(even) {
  background: #ddd;
}

ul:first-of-type {
  background: #888;
  color: #00f;
  position: relative;
}

#D ul li:nth-of-type(1) {
  width: 100px;
}

#D ul li:nth-of-type(2) {
  width: 200px;
}

#D ul li:nth-of-type(3) {
  width: 300px;
}
<div id="D">
  <ul id="R">
    <!-- 假行 Fake row -->
    <li>请不要说谎:</li>
    <li>这个不是表格 (table)!!!<br>
      <div style="position:relative; left:0; right:0;"><select style="width:100%;">
				    <option>全部</option>
			    </select></div>
    </li>
    <li>这是2D目录(ul和li)!!!</li>
  </ul>
</div>

注意:这是测试内容而非生产部分,因此请不要评论&lt; style&gt;在&lt; div&gt;中元素或为什么我不只是使用<table> 注意:这里使用“nth-of-type(1)”而不是“first-of-type”只是为了方便起见。

结果:第2列和第3列完美无缺。第一列仍为“自动” - 不是100px宽

我做错了什么?

0 个答案:

没有答案