简体   繁体   English

使用 javascript 更改 css 类样式

[英]Change css class style with javascript

Given the below css style, how can I reset the background-color with javascript?鉴于以下 css 样式,如何使用 javascript 重置背景颜色? Not just for the currently highlighted button, but for all those highlighted in the future?不仅针对当前突出显示的按钮,还针对将来突出显示的所有按钮?

#bottom_buttons > div.bottom_button.highlighted {
    background-color: #343434;
}

For instance: $("div.bottom_button.highlighted").css("background-color", "#e67300");例如: $("div.bottom_button.highlighted").css("background-color", "#e67300"); this works, but is overwritten as soon as the page changes.这有效,但一旦页面更改就会被覆盖。 IE loses focus or updates. IE 失去焦点或更新。

Similarly document.getElementById("bottom_button_" + button).style.backgroundColor = "#e67300";同样document.getElementById("bottom_button_" + button).style.backgroundColor = "#e67300"; works to change the numbered button on click, but also doesn't last.可以在单击时更改编号按钮,但也不会持久。

It's going to be difficult to have persistent changes in CSS from page to page with a refresh.通过刷新在页面之间对 CSS 进行持续更改将是困难的。 That being said you can do it with local storage.话虽如此,您可以使用本地存储来做到这一点。

Here's how you do it :这是你如何做到的:

 function overwriteStyles(styles) { var styleOverwrites = document.getElementById('style-overwrites'); if (styleOverwrites === null) { styleOverwrites = document.createElement('style'); styleOverwrites.id = 'style-overwrites'; document.head.appendChild(styleOverwrites); } styleOverwrites.innerHTML = styles; // Save styles to local storage localStorage.setItem('overridden-styles', styles); } // Here styles are grabbed from local storage and loaded for persistence document.addEventListener("DOMContentLoaded", function(event) { var styles = localStorage.getItem('overriden-styles'); if(styles != null) { overwriteStyles(styles); } }); // Example of overwriting styles overwriteStyles(` #bottom_buttons > div.bottom_button.highlighted { background-color: #e67300; } `);

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

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