简体   繁体   中英

Vanilla javascript - insertRule CSS not working

I currently have 3 inputs which are colour pickers.

<input type="color" name="seconds-hand" value="#0c82cc" />
<input type="color" name="minutes-hand" value="#0c82cc" />
<input type="color" name="hours-hand" value="#0c82cc" />

Ive then written some javascript to find each one of these and update the styles in the header:

const input = document.querySelectorAll('input');
const sheets = document.styleSheets;
const sheet = document.styleSheets[0];

function handleUpdate(){
    const element = document.getElementsByClassName(this.name);
    sheet.insertRule(`.${this.name} { background-color: ${this.value} }`);
    console.log(`.${this.name} { background-color: ${this.value} }`);
}
input.forEach(input => input.addEventListener('change', handleUpdate));
input.forEach(input => input.addEventListener('mousemovement', handleUpdate));

The console log is returning the correct style to add to the style sheet, but nothing is being added. Am i using the incorrect js .inserRule ? I cant figure out why it isn't changing.

Any help would be great.

The elements you were trying to find weren't in the DOM when the script ran. To fix this you can execute the code on window.onload event or DOMContentLoaded (document ready )

 window.onload = function(){ const input = document.querySelectorAll('input'); const sheets = document.styleSheets; const sheet = document.styleSheets[0]; function handleUpdate(){ const element = document.getElementsByClassName(this.name); sheet.insertRule(`.${this.name} { background-color: ${this.value} }`); console.log(`.${this.name} { background-color: ${this.value} }`); } input.forEach(input => input.addEventListener('change', handleUpdate)); input.forEach(input => input.addEventListener('mousemovement', handleUpdate)); } 
 <input type="color" class="seconds-hand" name="seconds-hand" value="#0c82cc" /> <input type="color" class="minutes-hand" name="minutes-hand" value="#0c82cc" /> <input type="color" class="hours-hand" name="hours-hand" value="#0c82cc" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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