从javascript更改css类[重复]

问题描述 投票:-3回答:5

这个问题在这里已有答案:

我想将一个元素的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 Variables所以我不能使用它,但我想要类似的东西。

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

javascript css css3 sass
5个回答
0
投票

在现代浏览器中,您可以使用:

document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyOtherClass');

虽然,为了完成你的具体案例,我会选择לבני מלכה的答案。


0
投票

也许使用适当的CSS代替:

window.innerHeight +'px'与使用100vh的高度相同。单位vh表示“视口高度”,100vh表示内窗的全高。

见:https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths


0
投票

在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>

0
投票

使用vh单位是这样做的正确方法..(虽然Mahboobeh Mohammadi说它与ios不兼容)height: 100vh;是视图的全高度..


-1
投票

对于普通的Js

function addClassById (_id,_class) {
  document.getElementById(_id).classList.add(_class);
}

function removeClassById (_id,_class) {
  document.getElementById(_id).classList.remove(_class);
}

addClassById("root","newClass")

我建议你使用JQUERY它很容易使用。将此cdn链接放在头标记上然后使用它。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

//This is for change css
$("#root").css({
"background-color": "yellow", 
"font-size": "200%"
});



 // This is how to add class
$("#root").addClass('newClass');





// This is how to remove class
 $("#root").removeClass('newClass')

我希望它对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.