简体   繁体   English

使用 vanilla js/css 根据条件更改按钮的颜色

[英]Change the colour of the button dependently on condition with vanilla js/css

I want to change the color of the button dependently on some condition.我想根据某些条件更改按钮的颜色。

In pseudo code it looks like this:在伪代码中它看起来像这样:

if(condition){
    myelememt.background = "something"
}

But it should be checked and applied before the page is loaded.但是应该在加载页面之前检查并应用它。

Thank you!谢谢!

Since you want it to apply the style before DOM paints, you can use DOMContentLoaded event, since this event fires as soon as the DOM nodes have finished loading, but before all assets, styles, etc... have been loaded.由于您希望它在 DOM 绘制之前应用样式,因此可以使用DOMContentLoaded事件,因为此事件会在 DOM 节点完成加载后立即触发,但在所有资产 styles 等...已加载之前。

Something like this should make it:这样的事情应该做到:

 const condition = true; document.addEventListener('DOMContentLoaded', (event) => { const button = document.querySelector('button'); if (condition) button.style.background = 'red'; });
 <html> <head> <meta charset="UTF-8" /> <script src="script.js"></script> <link rel="stylesheet" type="text/css" href="styles.css" /> </head> <body> <button>CLICK</button> </body> </html>

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

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