gpt4 book ai didi

javascript - 如何通过在 Javascript 中悬停将背景颜色更改为特定类

转载 作者:太空宇宙 更新时间:2023-11-03 21:22:02 25 4
gpt4 key购买 nike

我有三个 div 类的 colorBox。我想将鼠标悬停在他们每个人身上,当我这样做时,我希望他们每个人都将他们的背景颜色更改为不同的颜色。问题是..我不知道该怎么做。我假设您需要使用 this 关键字。但是,我认为我没有正确使用它

CSS

<style type="text/css">
.colorBox{ width:200px; min-height:300px; color:white;
background:black; display:inline-block; padding:0 7px; text-align:center; }
.colorBox h2 { border-bottom:2px solid white;}
</style>

HTML

<div class="colorBox"><h2>Text Header</h2><p>Asymmetrical wolf letterpress, photo booth cornhole occupy tattooed portland fanny pack distillery offal roof party blog. Health goth cray four loko flannel 8-bit organic, gochujang waistcoat. Keytar franzen mumblecore, ennui stumptown etsy meditation YOLO cray 3 wolf moon waistcoat pop-up poutine tattooed austin. Shabby chic brooklyn keytar normcore whatever <p></div>
<div class="colorBox"><h2>Text Header</h2><p>Asymmetrical wolf letterpress, photo booth cornhole occupy tattooed portland fanny pack distillery offal roof party blog. Health goth cray four loko flannel 8-bit organic, gochujang waistcoat. Keytar franzen mumblecore, ennui stumptown etsy meditation YOLO cray 3 wolf moon waistcoat pop-up poutine tattooed austin. Shabby chic brooklyn keytar normcore whatever <p></div>
<div class="colorBox"><h2>Text Header</h2><p>Asymmetrical wolf letterpress, photo booth cornhole occupy tattooed portland fanny pack distillery offal roof party blog. Health goth cray four loko flannel 8-bit organic, gochujang waistcoat. Keytar franzen mumblecore, ennui stumptown etsy meditation YOLO cray 3 wolf moon waistcoat pop-up poutine tattooed austin. Shabby chic brooklyn keytar normcore whatever <p></div>

Javascript

(function(){

var a = document.getElementsByClassName('colorBox');
this.a = a;
this.style.background = 'black';

function hoverColor()
{
if (this.a == a[0])
{
this.style.background = 'green';

}
else if(this.a == a[1])
{
this.style.background = 'blue';
}
else if(this.a == a[2])
{
this.style.background = 'red';
}
}

for(var i = 0; i < a.length; ++i)
{
a[i].addEventListener('mouseover', hoverColor.bind(this));
}

})();

最佳答案

(function(){

var a = document.getElementsByClassName('colorBox');

function addHover(index) {
return function(){
var backgroundColor = 'black';

switch (index) {
case 0:
backgroundColor = 'green';
break;
case 1:
backgroundColor = 'blue';
break;
case 2:
backgroundColor = 'red';
break;
}

if (a[index]) {
a[index].style.background = backgroundColor;
}
};
}

for (var i = 0; i < a.length; ++i) {
a[i].addEventListener('mouseover', addHover(i));
}

})();

关于javascript - 如何通过在 Javascript 中悬停将背景颜色更改为特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393943/

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