首页 > 解决方案 > 使用 javascript 更改 css 类样式

问题描述

鉴于以下 css 样式,如何使用 javascript 重置背景颜色?不仅针对当前突出显示的按钮,还针对所有将来突出显示的按钮?

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

例如: $("div.bottom_button.highlighted").css("background-color", "#e67300"); 这有效,但一旦页面更改就会被覆盖。IE 失去焦点或更新。

同样 document.getElementById("bottom_button_" + button).style.backgroundColor = "#e67300"; 可以在单击时更改编号按钮,但也不会持续。

标签: javascripthtmlcss

解决方案


刷新时很难在页面之间对 CSS 进行持久更改。话虽如此,您可以使用本地存储来做到这一点。

这是你如何做到的:

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;
  }
`);


推荐阅读