2017-02-09 23 views
0

我目前有3个输入,它们是拾色器。香草javascript - insertRule CSS不能正常工作

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

伊夫然后写一些JavaScript找到这些每一个更新的标题样式:

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

控制台日志返回正确的样式添加到样式表,但没有正在被添加。我是否使用不正确的js .inserRule?我不知道为什么它没有改变。

任何帮助将是伟大的。

+1

你是封装JS来确保DOM加载之前的JS是执行的代码? 将JavaScript放入(function(){...})()并重试 – PRDeving

+0

添加anon函数以确保DOM已加载并仍然不工作:( –

+0

它似乎工作正常,规则添加到样式表,在这里检查控制台中的对象https://jsfiddle.net/zsz2xxej/ –

回答

2

当脚本运行时,您尝试查找的元素不在DOM中。 为了解决这个问题,你可以在window.onload事件或DOMContentLoaded(文件就绪)

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" />

+0

另一个修正:可以添加与名称相同的类来查看实时更改