在下面,code snippet
我想在悬停的单个框上找到相同的名称类。
目前,我会jQuery
为所有代码单独编写代码,但我希望使用通用jQuery
代码,因为颜色框可能更像粉红色,黄色等。
因此,请帮助我为此添加通用代码。
简而言之,我想在单个框悬停时找到所有班级的相同名称。
jQuery('.red-box').hover(function (){
jQuery('.inner-box').removeClass('active');
jQuery('.red-box').addClass('active');
});
jQuery('.blue-box').hover(function (){
jQuery('.inner-box').removeClass('active');
jQuery('.blue-box').addClass('active');
});
jQuery('.green-box').hover(function (){
jQuery('.inner-box').removeClass('active');
jQuery('.green-box').addClass('active');
});
.inner-box {
height: 100px;
width: 100px;
border: 2px solid #000000;
float: left;
display: flex;
align-items: center;
justify-content: center;
}
.blue-box.active {
background-color: blue;
}
.red-box.active {
background-color: red;
}
.green-box.active {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-wrapper">
<div class="inner-box red-box">Red</div>
<div class="inner-box blue-box">Blue</div>
<div class="inner-box green-box">Green</div>
<div class="inner-box red-box">Red</div>
<div class="inner-box blue-box">Blue</div>
<div class="inner-box red-box">Red</div>
<div class="inner-box green-box">Green</div>
<div class="inner-box blue-box">Blue</div>
</div>
悬停时,首先添加活动类。然后,检查具有相同类的当前元素的兄弟姐妹,然后也将active添加到这些元素。
jQuery(".inner-box").hover(function(){
$(this)[0].classList.add("active");
var classList = $(this)[0].classList; // returns inner-box, red-box or blue-box
var siblings = $(this).siblings();
$(siblings).each(function(index,elem){
if($(elem).hasClass(classList[1])){ // check if other elements have the same class as of the current element and add active.
$(this)[0].classList.add("active");
}else{
$(this)[0].classList.remove("active");
}
})
});
.inner-box {
height: 100px;
width: 100px;
border: 2px solid #000000;
float: left;
display: flex;
align-items: center;
justify-content: center;
}
.blue-box.active {
background-color: blue;
}
.red-box.active {
background-color: red;
}
.green-box.active {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-wrapper">
<div class="inner-box red-box">Red</div>
<div class="inner-box blue-box">Blue</div>
<div class="inner-box green-box">Green</div>
<div class="inner-box red-box">Red</div>
<div class="inner-box blue-box">Blue</div>
<div class="inner-box red-box">Red</div>
<div class="inner-box green-box">Green</div>
<div class="inner-box blue-box">Blue</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句