首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现div子元素的getComputedStyle?

如何实现div子元素的getComputedStyle?
EN

Stack Overflow用户
提问于 2022-03-26 02:15:31
回答 1查看 62关注 0票数 0

抱歉,提前为ESL选择单词。我想得到的是相邻(?)的一个getComputedStyle的h3。或相关的(?)对于具有特定类(mainBook)的div,而h3没有任何类。

下面是CSS的一个示例:

代码语言:javascript
复制
.mainBook 
{
     position: absolute;
}   
.mainBook h3
{
     line-height: 120px;
}

我知道如何getComputedStyle of mainBook:

代码语言:javascript
复制
const element = document.querySelector('.mainBook');
const style = getComputedStyle(element);
// and then if I want: style.getPropertyValue("nameOfProperty")

下面是HTML:

代码语言:javascript
复制
<div class="mainBook">
        <h3>Title</h3>
</div>

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

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

但是,除了h3,还有什么办法可以做到吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-26 02:53:46

1)可以将h3元素作为

代码语言:javascript
复制
const element = document.querySelector('.mainBook h3');

并将其lineHeightcomputedStyle获得如下所示:

代码语言:javascript
复制
const style = getComputedStyle(element);
let lineHeight = style.lineHeight.

代码语言:javascript
复制
const element = document.querySelector('.mainBook h3');
const style = getComputedStyle(element);
console.log(style.lineHeight)
代码语言:javascript
复制
.mainBook {
  position: absolute;
}

.mainBook h3 {
  line-height: 120px;
}
代码语言:javascript
复制
<div class="mainBook">
  <h3>Title</h3>
</div>

2)还可以从mainBook元素中获取h3元素,如下所示:

代码语言:javascript
复制
const mainBookEl = document.querySelector('.mainBook');
const headingEl = mainBookEl.querySelector('h3')
const style = getComputedStyle(headingEl);
const lineHeight = style.lineHeight;

代码语言:javascript
复制
const mainBookEl = document.querySelector('.mainBook');
const headingEl = mainBookEl.querySelector('h3')
const style = getComputedStyle(headingEl);
console.log(style.lineHeight)
代码语言:javascript
复制
.mainBook {
  position: absolute;
}

.mainBook h3 {
  line-height: 120px;
}
代码语言:javascript
复制
<div class="mainBook">
  <h3>Title</h3>
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71624809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档