首页 > 解决方案 > 从 javascript 更改 css 类

问题描述

我想将一个元素设置为heightwindow.innerheight但我必须在 CSS 中进行设置,因为不知何故我无法访问该元素以使用 javascript 来更改它的样式。有没有办法做到这一点?就像在 javascript 中更改 CSS 类一样?

我试过这个:

document.getElementById('root').style.setProperty('--view-height', window.innerHeight +'px');

在 CSS 中:

.menu {
    height: var(--view-height) !important;
}

它可以工作,但旧浏览器不支持CSS 变量,所以我不能使用它,但我想要类似的东西。

编辑:有很多答案,但他们都使用 javascript,我说我不能使用 js 来设置元素样式!我只想通过 css 类风格来做

标签: javascriptcsssass

解决方案


在javascript中设置height而不是使用variables

document.getElementById('root').style.height=window.innerHeight +'px';

参见示例:

 document.getElementById('root').style.height=window.innerHeight +'px';
#root{
background-color:red;
}
<div id="root"></div>

对您的编辑无用 js 使用height:100vh;

#root{
height:100vh;
background-color:red;
}
<div id="root"></div>


推荐阅读