简体   繁体   English

使用JavaScript更改CSS文件属性值

[英]change css file attribute values using JavaScript

What is the proper and fastest way to change CSS values using JavaScript? 使用JavaScript更改CSS值的正确,最快的方法是什么? For example, if I have a style.css file: 例如,如果我有一个style.css文件:

#h1 {
 color: 'red';
}

I need to change the color to any other color and update the CSS file. 我需要将颜色更改为任何其他颜色并更新CSS文件。

document.querySelector('#h1').style.color = 'your-color';

JS: JS:

document.getElementById("elementsId").style.color= "red";

My recommendation would be not to use Id name like h1 as it may be confusing with the <h1> tag in html. 我的建议是不要使用像h1这样的ID名称,因为它可能与html中的<h1>标记混淆。 Use more clear variable name like headerId . 使用更清晰的变量名称,例如headerId

for changing multiple css properties use this: 要更改多个CSS属性,请使用以下命令:

document.getElementById(elementsId).setAttribute("style","wi‌​dth: 500px; background-color: yellow;");

对于多个CSS属性更改,请使用classname add .it减少dom中的代码行

document.querySelector('#h1').classList.add('your-class')

 $('h1').css('color','#ff5722'); 
 #h1 { color: 'red'; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1> this color tho</h1> 

Jquery is from javascript so once you learn jquery you will sometimes go back to javascript jQuery来自javascript,因此一旦您学习了jQuery,有时就会回到javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM