简体   繁体   English

获取CSS属性 <ul><li> 子节点与香草javascript

[英]Get CSS property of <ul> <li> child node with vanilla javascript

How can I get CSS properties of an child element of a node? 如何获取节点的子元素的CSS属性? I want to get the height of the <li> element of a <ul> 我想获得<ul><li>元素的高度

style.scss style.scss

ul.menu {
   width: 100%;
   float: left;
   li {
      height: 28px;
    }
}

javascript JavaScript的

let elementList = this.dropdownMenu.nativeElement.children;
console.log(elementList.length);
console.log(/*height of li*/);

I prefer solutions with vanilla JavaScript without using jQuery! 我更喜欢使用vanilla JavaScript的解决方案而不使用jQuery!

For your case, where the html looks like: 对于你的情况,html看起来像:

<ul class="menu">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

And css: 和css:

ul.menu {
   width: 100%;
   float: left;
}

ul.menu li {
  height: 28px;
}

Your working javascript should be: 你的工作javascript应该是:

var list = document.getElementsByClassName("menu")[0];

for (var i = 0; i < list.children.length; ++i) {
    var clientHeight = list.children[i].clientHeight,
        offsetHeight = list.children[i].offsetHeight;
    console.log(clientHeight); // with padding
    console.log(offsetHeight); // with borders
}

See also this answer . 另见这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM