要求: 当每种颜色发生变化时,html 将显示
linear-gradient(to right,rgb(x,x,x),rgb(x,x,x))
但是每次颜色变化时我的代码都会显示。
我不需要每次都出现,只需更改 rgb 的值
是否有改进的方法来显示线性渐变?
在我的 js 中:
var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById("gradient");
function setGradient() {
body.style.background =
"linear-gradient(to right, "
+ color1.value
+ ", "
+ color2.value
+ ")";
css.textContent = body.style.background + ";";
}
//set initial value in the first load page
setGradient();
//display linear gradient value
body.addEventListener("input",function(){
var p = document.createElement("p")
p.appendChild(document.createTextNode("linear-gradient(to right,"+
color1.value+ ","+ color2.value+ ")"));
body.appendChild(p);
})
color1.addEventListener("input", setGradient);
color2.addEventListener("input", setGradient);
在我的 html 中:
<h1>Background Generator</h1>
<input class="color1" type="color" name="color1" value="#00ff00">
<input class="color2" type="color" name="color2" value="#ff0000">
<h2>Current CSS Background</h2>
在我的 CSS 中:
body {
font: 'Raleway', sans-serif;
color: rgba(0,0,0,.5);
text-align: center;
text-transform: uppercase;
letter-spacing: .5em;
top: 15%;
background: linear-gradient(to right, red , yellow); /* Standard
syntax */
}
最佳答案
这是你如何做到的,使用document.querySelectorAll
,然后绑定(bind)change
的事件监听器。请注意 css.textContent = body.style.background + ";";
设置在 setGradient()
之后和 change
事件监听器
var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById("gradient");
function setGradient() {
body.style.background =
"linear-gradient(to right, "
+ color1.value
+ ", "
+ color2.value
+ ")";
}
//set initial value in the first load page
setGradient();
css.textContent = body.style.background + ";";//for first initialization
//display linear gradient value
var elementsArray = document.querySelectorAll('.color1, .color2');//store the input to var
elementsArray.forEach(function(elem) {//iterate it, and bind change event listener for each
elem.addEventListener("change",function(){
css.textContent = body.style.background + ";";
})
});
color1.addEventListener("input", setGradient);
color2.addEventListener("input", setGradient);
body {
font: 'Raleway', sans-serif;
color: rgba(0,0,0,.5);
text-align: center;
text-transform: uppercase;
letter-spacing: .5em;
top: 15%;
background: linear-gradient(to right, red , yellow); /* Standard
syntax */
}
<body id="gradient">
<h1>Background Generator</h1>
<input class="color1" type="color" name="color1" value="#00ff00">
<input class="color2" type="color" name="color2" value="#ff0000">
<h2>Current CSS Background</h2>
<h3>
</h3>
</body>
关于javascript - 如何不增加显示p元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463474/