简体   繁体   English

在DOM上使用Vanilla js样式化CSS时,是否总是内联样式?

[英]When styling a css by using vanilla js on the DOM is it always inline styles?

I'm messing around with vanilla JavaScript and I noticed that when styling a document with js in the DOM the styles are inline. 我搞砸了香草JavaScript,发现在DOM中使用js样式化文档时,样式是内联的。 Is there a way to style a style sheet with javascript used on the DOM or is styling with Javascript bad practice? 有没有一种方法可以使用DOM上使用的javascript来样式化样式表,或者是使用JavaScript的不良做法来进行样式化? I was thinking it might have some uses when parts of a website change with user interaction, but I'm guessing the same thing can be accomplished with css pseudo classes. 我以为当网站的某些部分随着用户交互而改变时,它可能会有一些用处,但是我猜测使用CSS伪类可以完成相同的事情。 To reiterate my question can you use javascript to style a stylesheet in the DOM or is it just inline and bad practice? 要重申我的问题,您可以使用javascript在DOM中设置样式表的样式还是只是内联和不良做法?

body.style.backgroundColor= "blue";

Best practice, in my opinion, is to create classes in separate CSS file and then change element classes using JS. 我认为,最佳实践是在单独的CSS文件中创建类,然后使用JS更改元素类。 It looks better and also it is easier to read and understand. 它看起来更好,也更容易阅读和理解。

But if you want to, you can change stylesheet. 但是,如果您愿意,可以更改样式表。 Read this Is it possible to alter a CSS stylesheet using JavaScript? 阅读本文是否可以使用JavaScript更改CSS样式表? (NOT the style of an object, but the stylesheet itself) (不是对象的样式,而是样式表本身)

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

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