js 通过button按钮onclick事件改变背景颜色 如何切换性改变?

如题所述

第1个回答  推荐于2019-10-09
<HTML>
<head>
<script>
function mychange()
{
var color = document.getElememtById("colorType").value;
if(color == "red")
{

document.getElementById("div1").style.background="blue";
document.getElememtById("colorType").value = "blue";
}
else if(color == "blue")
{
document.getElementById("div1").style.background="red";
document.getElememtById("colorType").value = "red";
}

}
</script>
</head>
<body>
<table id="div1" style="height:80px; width:800px; background:red">
<input type="hidden" value="red" id="colorType" />
<input type="button" value="第一个按钮" onclick="mychange()" />
</table>

</body>
</HTML>

这是一种简单的方式实现。还有很多中解决方案,你可以再拓展一下。本回答被网友采纳
第2个回答  2018-05-23

默认“今日”是选中状态,是行内样式:

<button type="button" id="today" class="btn-link" onclick="todayDate()" style="color: #0062CC;">今日</button>

上面的日期都是点击才会切换颜色:

点击其它颜色,“今日”颜色更换成灰色

再次点击“今日”,还原回默认状态颜色

在除“今日”外的其它任一个日期中添加一个点击事件,可以实现【改变“今日”默认颜色状态】

在“今日”的点击事件中添加【还原‘‘今日’’的默认状态颜色】

第3个回答  2017-12-27
对于几位回答问题的js水平实在不敢恭维:
回答问题不要偷换概念弄两个按钮来回切换、更要懂得标准的写法。
那style.backgroundColor不是style.background
虽然有的浏览器可以识别background,也只是浏览器容错能力好,不要将错就错。
var colorTag = 1;
var colors = ["#ff0000", "#0000ff"];
function mychange()
{
colorTag = 1 - colorTag;
document.getElementById("div1").style.backgroundColor = colors[ colorTag];

}
你试试看?
相似回答