第n个孩子未按预期选择所有孩子

时间:2018-07-19 14:53:14

标签: javascript html css

我在CSS中使用nth-child作为伪类,但它似乎没有按预期工作。通过执行nth-child(-n + 3),应该将CSS添加到h4的前三个元素中。例如,

$scope.GetStateByComponents = function() {
  var res = false;
  Object.keys($scope.componentsHelper).forEach(function(key) {
    angular.forEach($scope.componentsHelper[key].commandStateTypes, function(value, key) {
      if (value.name == null) {
        res = true;
        $scope.componentStates[{
          name: value.name,
          state: res
        }];
      }
    });
    return res;
  });
}
  • n = 0-> 3
  • n = 1-> 2
  • n = 2-> 1
  • 因为我们没有第0个孩子而停止活动

但是,当我在两个H4之间有一个H1时,我不会出现这种情况。这是我的代码。

h4:nth-child(-n + 3) {color: white}
var text = document.createElement("h1");
text.innerHTML = "YOLOOO"
document.getElementById("homeBase").appendChild(text);

for (var i = 0; i < 4; i++) {
  var el = document.createElement("h4");
  el.innerHTML = "Hey";
  document.getElementById("homeBase").appendChild(el);
}
#homeBase {
  width: 100%;
  height: 100%;
  background-color: red;
}

h4:nth-child(-n + 3) {
  color: white;
}

h4 {
  color: black;
}

#homeBase:hover {
  background: blue;
}

@keyframes pulse {
  0% {
    background-color: pink;
  }
  100% {
    background-color: blue;
  }
}

body,
html {
  width: 100%;
  height: 100%;
}

为什么会这样?还是我只是缺少一些简单的东西?白色只有2 H $,而不是3。

1 个答案:

答案 0 :(得分:1)

nth-child关心元素是否是父级的编号子级。请改用nth-of-type

var text = document.createElement("h1");
text.innerHTML = "YOLOOO"
document.getElementById("homeBase").appendChild(text);

for (var i = 0; i < 4; i++) {
  var el = document.createElement("h4");
  el.innerHTML = "Hey";
  document.getElementById("homeBase").appendChild(el);
}
#homeBase {
  width: 100%;
  height: 100%;
  background-color: red;
}

h4:nth-of-type(-n + 3) {
  color: white;
}

h4 {
  color: black;
}

#homeBase:hover {
  background: blue;
}

@keyframes pulse {
  0% {
    background-color: pink;
  }
  100% {
    background-color: blue;
  }
}

body,
html {
  width: 100%;
  height: 100%;
}
<div id="homeBase">
  <h4>Yo</h4>
</div>

相关问题