【问题标题】:How I can get css property and change the height of html element by javascript如何获取 css 属性并通过 javascript 更改 html 元素的高度
【发布时间】:2020-08-31 22:43:18
【问题描述】:

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

我的 CSS 是:

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

我将这段代码用于脚本:

 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 返回空值。 请帮助我提前谢谢

【问题讨论】:

  • 你的代码不完整,请用完整的js代码编辑你的问题
  • 是的,这段代码在for循环中使用,我编辑它
  • 你先创建了div标签但没有附加到Dom,然后你想选择它,答案绝对是null,必须先附加到Dom然后选择它
  • 但是,您不应该在选择器'getElementById'中输入#号
  • 在下一行中,我将其附加到表格单元格中 cell.appendChild(div);我编辑的是

标签: javascript css dom responsive-design css-selectors


【解决方案1】:

删除#indicator 中的#getElementById() id 名称前不需要# 符号

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

如果你想动态改变indicatorheight

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

【讨论】:

  • 您的<script> 标签是否位于<body> 标签的末尾?您的 javascript 代码在加载之前看不到 indicator div
  • 当我使用 div[].style.height ='15px';工作正常,但我想动态改变高度,因为我的 CSS 类是动态的
  • 我编辑了动态变化的问题。如果您正确使用 script 标签,此代码应该可以工作。希望这会有所帮助。
【解决方案2】:

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

div.className='indicator';

【讨论】:

    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2017-01-30
    • 2011-11-30
    相关资源
    最近更新 更多