如何使用javascript设置:: before选择器的元素高度?

时间:2014-12-08 12:34:38

标签: javascript css

有一个带.bg类的元素。 css规则如下:

.bg {
    width:100%;
}

.bg:before {
    position: absolute;
    content: '';
    background: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
}

我有一个javascript规则,我将高度设置为bg类:

$(".bg").height($(document).height());

但我想将$(document).height()设置为.bg:before。我怎样才能通过javascript实现这一目标? 因为$(".bg:before").height($(document).height());不起作用。

提前致谢

2 个答案:

答案 0 :(得分:1)

使用JavaScript,您可以通过这种方式修改.bg:before的规则。

循环遍历样式表中的规则,如果当前规则为.bg:beforer.selectorText == .bg:before),请更改其heightr.style.height = window.innerHeight + 'px')。



var ss = document.styleSheets;

for (i = 0; i < ss.length; i++) {
  var rules = ss[i];
  for (j = 0; j < rules.cssRules.length; j++) {
    var r = rules.cssRules[j];
    if (r.selectorText == ".bg:before" || r.selectorText == ".bg::before") {
      console.log('Old rule: ' + r.cssText)
      r.style.height = window.innerHeight + 'px';
      console.log('Modified rule: ' + r.cssText)
    }
  }
}
&#13;
.bg {
  width: 100%;
}
.bg::before {
  position: absolute;
  content: '';
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 100%;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你根本无法使用javascript,因为伪元素不是DOM的一部分。