【问题标题】:How to getComputedStyle of sub-element of div?如何获取div子元素的ComputedStyle?
【发布时间】:2022-03-26 11:02:22
【问题描述】:

提前为 ESL 的单词选择感到抱歉。我试图得到的是与具有特定类(mainBook)的div相邻(?)或相关(?)的h3的getComputedStyle,而h3没有。

这是 CSS 的一个示例:

.mainBook 
{
     position: absolute;
}   
.mainBook h3
{
     line-height: 120px;
}

我知道如何获取 mainBook 的ComputedStyle:

const element = document.querySelector(\'.mainBook\');
const style = getComputedStyle(element);
// and then if I want: style.getPropertyValue(\"nameOfProperty\")

这是 HTML:

<div class=\"mainBook\">
        <h3>Title</h3>
</div>

不确定这是否有帮助,但是:

const element = document.querySelector(\'.mainBook\');
    const style = getComputedStyle(element);
    // and then if I want: style.getPropertyValue(\"line-height\");
    // How do I getComputedStyle the h3?
.mainBook 
    {
         position: absolute;
    }   
    .mainBook h3
    {
         line-height: 120px;
    }
<div class=\"mainBook\">
            <h3>Title</h3>
    </div>

但是除了h3还有什么方法可以做同样的事情吗?

谢谢!

  • 发布相关的 HTML,然后将所有的 HTML、CSS 和 JavaScript 制作成 minimal reproducible example
  • @zer00ne 完成。希望它符合要求的标准。

标签: javascript html css document getcomputedstyle


【解决方案1】:

1)您可以将h3 元素作为

const element = document.querySelector('.mainBook h3');

并从computedStyle 获取它的lineHeight

const style = getComputedStyle(element);
let lineHeight = style.lineHeight.

const element = document.querySelector('.mainBook h3');
const style = getComputedStyle(element);
console.log(style.lineHeight)
.mainBook {
  position: absolute;
}

.mainBook h3 {
  line-height: 120px;
}
<div class="mainBook">
  <h3>Title</h3>
</div>

2)您还可以从 mainBook 元素中获取 h3 元素:

const mainBookEl = document.querySelector('.mainBook');
const headingEl = mainBookEl.querySelector('h3')
const style = getComputedStyle(headingEl);
const lineHeight = style.lineHeight;

const mainBookEl = document.querySelector('.mainBook');
const headingEl = mainBookEl.querySelector('h3')
const style = getComputedStyle(headingEl);
console.log(style.lineHeight)
.mainBook {
  position: absolute;
}

.mainBook h3 {
  line-height: 120px;
}
<div class="mainBook">
  <h3>Title</h3>
</div>

【讨论】:

  • 有效!我几乎可以肯定我尝试过 (querySelector('.mainBook h3')) 但我一定做错了什么。谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2013-06-13
  • 2020-10-30
  • 1970-01-01
  • 2014-03-27
相关资源
最近更新 更多