javascript - 从 javascript 更改 css 类
问题描述
我想将一个元素设置为height
,window.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 类风格来做
解决方案
在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>
推荐阅读
- java - 在将 JSON 转换为 XML 时添加额外的元数据
- image - 有效存储和检索的图像缓存机制
- c#-4.0 - 看起来我们不支持这种文件格式
- azure - Helm 不接受值 YAML
- azure-active-directory - 从 ARM 模板获取服务主体 ID
- java - 计算字符串中的字符频率(Java)
- c++ - 将 countNonZero 返回值转换为百分比
- php - Yii2:我可以在验证器之前设置访问行为吗?
- amazon-web-services - Kubernetes:不同的应用程序需要单独的部署和服务文件吗?
- excel - 比较两个表并在 excel 中提及新更改的值