如何通过javascript获取css属性并改变html元素的高度?

问题描述 投票:-1回答:1

我尝试创建一个div元素,并从CSS选择器中读取高度,最后通过javascript改变div元素的高度。当我使用 div.style.height ='15px'; 工作正常,但我想动态改变高度,因为我的CSS类将通过响应功能改变。

我的CSS是

    #indicator {
        width: 15px;
        height: 15px;
    }

我的CSS是: 我用这段代码做脚本。

 div = document.createElement("div");// valve_indicator
 div.style.border = '1px solid #b3280a';

 div.style.height =document.getElementById('indicator').style.height; // instead div.style.height ='15px';
 div.style.width = '15px';
 cell.appendChild(div); // cell is a table cell

但是 document.getElementById('indicator').style.height 返回null.please help me in advance谢谢

javascript html css dom css-selectors
1个回答
1
投票

移除 ##indicator. getElementById() 不需要 # 逗号

document.getElementById('indicator').style.height

如果你想动态地改变你的 indicator height:

let indicator = document.getElementById('indicator');
indicator.addEventListener("change", function(){
    div.style.height = indicator.style.height;
}) 

0
投票

我用这个代码解决了我的问题

div.className='indicator';
© www.soinside.com 2019 - 2024. All rights reserved.