Onclick更改div图像以及背景色

时间:2018-09-06 18:26:40

标签: javascript html

我在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>

2 个答案:

答案 0 :(得分:2)

您已经有一个名为“属性”的变量,可以使用它。

将您的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;
}

答案 1 :(得分:1)

问题是您有重复的ID。

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

您可以附加一些内容以使其与众不同。另外,我也同意更改状态逻辑。

13
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;

}

相关问题