单击更改div图像以及背景颜色



我有一个图像作为div内的按钮。默认情况下,当我单击div 时,我显示带有背景绿色的 image1,我应该将背景颜色更改为蓝色并更改为 image2。现在我只能更改颜色,而不能更改图像。如何更改图像和背景颜色?

var count = 0;

function setColor(id) {
var property = document.getElementById(id);
if (count == 0) {
property.style.backgroundColor = "blue";
document.getElementById('1').src = '~/Images/Icons/image1.png';
count = 1;
} else {
property.style.backgroundColor = "green";
document.getElementById('1').src = '~/Images/Icons/image2.png';
count=0
}
}
.buttonclass {
	margin-left: 30px;
	margin-bottom: 2px;
	margin-top: 2px;
	width: 25px;
	height: 25px;
	box-sizing: border-box;
	vertical-align: middle;
	text-align: center;
	position: absolute;
	z-index: 100000;
	border: solid 1px #777;
	background-color: green;
	padding: 0px;
}
<div class="buttonclass" id="1" onclick="setColor(1);" >
<img id="1" src="~/Images/Icons/image1.png">
</div>

你已经有一个名为"property"的变量,你可以使用它。

将 JavaScript 更改为:

var count = 0;  
function setColor(id) {
var property = document.getElementById(id);
if (count == 0) {
property.style.backgroundColor = "blue";
property.src = '~/Images/Icons/image1.png';
count = 1;
} else {
property.style.backgroundColor = "green";
property.src = '~/Images/Icons/image2.png';
count=0
}
}

或者,您可以将其缩短为:

var count = 0;
const COLORS = [
"blue",
"green"
];
function setColor(id) {
var property = document.getElementById(id);
property.style.backgroundColor = COLORS[count]
property.src = ('~/Images/Icons/image' + count + '.png';
var count = count == 0 ? 1 : 0;
}

问题是您有重复的 ID。

如图所示: ID 在页面中应该是唯一的。但是,如果存在多个具有指定 ID 的元素,则 getElementById(( 方法将返回源代码中的第一个元素。

您可以附加一些内容以使它们与众不同。此外,我获得了更改状态逻辑的权限。

var initial = true;

function setColor(id) {
var property = document.getElementById(id+"div");
var propertyImg = document.getElementById(id+"img");
if (initial) {
property.style.backgroundColor = "blue";
propertyImg.src = '~/Images/Icons/image1.png';
} else {
property.style.backgroundColor = "green";
propertyImg.src = '~/Images/Icons/image2.png';
}
initial = !initial;
}
.buttonclass {
	margin-left: 30px;
	margin-bottom: 2px;
	margin-top: 2px;
	width: 25px;
	height: 25px;
	box-sizing: border-box;
	vertical-align: middle;
	text-align: center;
	position: absolute;
	z-index: 100000;
	border: solid 1px #777;
	background-color: green;
	padding: 0px;
}
<div class="buttonclass" id="1div" onclick="setColor(1);" >
<img id="1img" src="~/Images/Icons/image1.png">
</div>

最新更新