gpt4 book ai didi

javascript - 使用 Javascript 在悬停和单击时切换 CSS 背景颜色

转载 作者:行者123 更新时间:2023-11-28 07:25:53 24 4
gpt4 key购买 nike

我一直在使用此脚本在单击时切换 CSS 背景颜色,并且我一直在尝试更改它,以便第二种颜色将在悬停时出现,而 将在单击时出现。任何人都可以帮助让它发挥作用吗?

这是我的 jsfiddle 链接:

https://jsfiddle.net/pkrWV/70/

var bodyObj, className, index;

bodyObj = document.getElementById('body');
index = 1;
className = [
'imageOne',
'imageTwo',
'imageThree',
];

function updateIndex(){
if(index === 0){
index = 1;
}else{
index = 0;
}
}

bodyObj.onclick = function(e){
e.currentTarget.className = className[index];
updateIndex();
}

最佳答案

如果你想在悬停时改变颜色,你只需要定义hover您类(class)的选择器。像这样 -

#body.imageOne:hover {
background-color: red;
}

var bodyObj, className, index;

bodyObj = document.getElementById('body');
index = 1;
className = [
'imageOne',
'imageTwo',
'imageThree',
];

function updateIndex() {
if (index === 0) {
index = 1;
} else {
index = 0;
}
}

bodyObj.onclick = function(e) {
e.currentTarget.className = className[index];
updateIndex();
}
html,
body,
#body {
height: 100%;
width: 100%;
}
#body.imageOne {
background-color: green;
}
/*Add this */

#body.imageOne:hover {
background-color: red;
}
#body.imageTwo {
background-color: red;
}
#body.imageThree {
background-color: black;
}
<div id="body" class="imageOne"></div>

关于javascript - 使用 Javascript 在悬停和单击时切换 CSS 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com