首页 > 解决方案 > setAttribute 不覆盖另一个类属性

问题描述

我创建了一个代码,当您在我的网站正文的选择中选择一个选项时,会在类中包含一个带有 setAttribute 的新属性,但我的问题是它删除了暗模式的另一个属性。

代码的目的是更改网站的某些颜色,并将其保存到本地存储中。

我能改变什么?

function wow(value) { 
 var index = { 
 chb: "griegos", 
 cj: "romanos", 
 hv: "celtas" 
 }; 
 document.getElementById("body").setAttribute("class", index[value]);}
.griegos {background: orange}
.romanos {background: purple}
.celtas {background: green}
<body id="body" class="griegos dark">
<select class="forminput" onchange="wow(this.value)"><option value="chb">Camp Half-Blood</option><option value="cj">Camp Jupiter</option><option value="hv">Hotel Valhalla</option></select></div>

标签: javascripthtmlcss

解决方案


一种选择如下;使用Element.classListAPI:

// ensuring that we look for elements after the document
// is loaded and elements are present, by waiting for
// the 'DOMContentLoaded' event to fire:
window.addEventListener('DOMContentLoaded', () => {
  // named function, which receives the 'evt' 
  // (a reference to the Event Object) passed
  // automatically from the (later) use of
  // EventTarget.addEventListener():
  function wow(evt) {

    var index = {
      chb: "griegos",
      cj: "romanos",
      hv: "celtas"
    };

    // here we look for the relevant element via its
    // id:
    document.getElementById("body")
      // we use Element.classList.remove() to remove
      // previously-chosen class-names:
      .classList.remove(
        // we use an Array-literal with the spread
        // syntax to create an Array of the options
        // within the <select>:
        [...evt.target.options]
          // Array.prototype.map() lets us to return
          // a new Array based on the former Array:
          .map(
            // and here we pass the relevant class-name
            // returned from the index Object based on
            // the current option's value:
            (opt) => index[opt.value]
        )
      );
    // once those class-names are removed, we once again
    // select the relevant element based on its id, and
    // use Element.classList.add() to add the relevant
    // class-name, again from the index Object:
    document.getElementById("body").classList.add(
      index[evt.currentTarget.value]
    );
  }

// here use document.querySelector() to find the <select>
// element using a CSS selector:
document.querySelector('select.forminput')
  // and bind the event-handling using
  // EventTarget.addEventListener(), to bind the wow()
  // function to handle the 'change' event:
  .addEventListener('change', wow);
});
.griegos {
  background: orange
}

.romanos {
  background: purple
}

.celtas {
  background: green
}
<body id="body" class="griegos dark">
  <select class="forminput">
    <option value="chb">Camp Half-Blood</option>
    <option value="cj">Camp Jupiter</option>
    <option value="hv">Hotel Valhalla</option>
  </select>
</body>

JS 小提琴演示


推荐阅读