【问题标题】:Button Function one time按键功能一次
【发布时间】:2021-05-22 07:04:34
【问题描述】:
所以我正在尝试创建一个可以使用 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">
【问题讨论】:
标签:
javascript
html
function
button
【解决方案1】:
当你写作时:
const color = document.getElementById('colorPick').value;
您会立即获取颜色值,而不是缓存元素,这意味着您不能再次使用它。
改为:
const color = document.getElementById('colorPick');
在您的函数中,只需将color.value 分配给后台即可。
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">
【解决方案2】:
作为第二种解决方案,如果您愿意您可以移除不需要更改颜色的按钮。
const color = document.getElementById('colorPick');
function changeCol() {
document.body.style.backgroundColor = color.value;
}
<input type="color" id="colorPick" onchange="changeCol()">