You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮修改div背景色后立即变回白色的问题求助

问题解决方法

你的问题出在按钮嵌套在<form>标签里——浏览器默认会把form里的按钮识别为提交按钮,点击后会触发表单提交,导致页面刷新,刚设置的背景色自然就被重置了。虽然你的ChangeColor函数写了return false,但没在onclick里生效,所以起不到阻止作用。

给你三种简单的解决办法:

方法1:让onclick接收函数的返回值

直接修改按钮的onclick属性,加上return:

<button id="GETid" onclick="return ChangeColor()">GET</button>

这样函数返回的false会阻止浏览器的默认提交行为,页面就不会刷新了。

方法2:在函数里阻止事件默认行为

修改函数,添加事件参数并调用preventDefault():

function ChangeColor(event){
    event.preventDefault(); // 阻止默认提交动作
    var divElement = document.getElementById("GETResponse");
    var randomColor = "#" + Math.floor(Math.random()*16777215).toString(16);
    divElement.style.backgroundColor = randomColor;
}

然后按钮的onclick要传递事件参数:

<button id="GETid" onclick="ChangeColor(event)">GET</button>

方法3:把按钮类型设为button

form里的按钮默认类型是submit,直接给按钮加上type="button",让它不再触发表单提交:

<button id="GETid" type="button" onclick="ChangeColor()">GET</button>

这个方法最简单,不用修改JS代码。

内容的提问来源于stack exchange,提问作者Nexx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:14:52