按钮功能一次



所以我正在尝试创建一个可以使用colorPicker更改背景的页面。它确实有效,只有当我更改它时,我才能在不刷新页面的情况下再次更改它。例如,我将BGCR更改为红色,但要将其更改为黄色,我必须刷新页面。那么我该怎么做才能让它发挥作用呢?这是代码:

const color = document.getElementById('colorPick').value
document.getElementById('changeColor').onclick = changeCol
function changeCol() {
document.body.style.backgroundColor = color
}
<input id="changeColor" type="button" value="Change the Color">
<input type="color" id="colorPick">

编写时:

const color = document.getElementById('colorPick').value;

您将立即获取颜色值,而不是缓存元素,这意味着您不能再次使用它。

相反:

const color = document.getElementById('colorPick');

在您的函数中,只需将CCD_ 1分配给后台即可。

const color = document.getElementById('colorPick');
document.getElementById('changeColor').onclick = changeCol;
function changeCol() {
document.body.style.backgroundColor = color.value;
}
<input id="changeColor" type="button" value="Change the Color">
<input type="color" id="colorPick">

作为第二个解决方案,如果您想要,您可以删除更改颜色所不需要的按钮。

const color = document.getElementById('colorPick');
function changeCol() {
document.body.style.backgroundColor = color.value;
}
<input type="color" id="colorPick" onchange="changeCol()">

最新更新