我在悬停功能的按钮中有 5 个具有不同类型颜色的 css 类,在我的页面中可能有 5 个具有不同类的按钮。当我将鼠标悬停在每个按钮上时,颜色应该根据各自的类名设置,到目前为止它对我来说工作正常。但现在我可以看到巨大的代码,我想把它变小。请推荐任何人。
$('[class^="button"]').parent().each(function(){
var parentElement = $(this);
var buttonfullwidth = $(parentElement).hasClass('buttonfullwidth');
var buttonfullwidth_1 = $(parentElement).hasClass('buttonfullwidth_1');
var buttonfullwidth_2 = $(parentElement).hasClass('buttonfullwidth_2');
var buttonfullwidth_3 = $(parentElement).hasClass('buttonfullwidth_3');
var buttonfullwidth_4 = $(parentElement).hasClass('buttonfullwidth_4');
if(buttonfullwidth_1 !== false) {
$(parentElement).hover(function(){
$(this).addClass('buttonfullwidth_1');
}, function(){
$(this).removeClass('buttonfullwidth_1');
});
}
if(buttonfullwidth_2 !== false) {
$(parentElement).hover(function(){
$(this).addClass('buttonfullwidth_2');
}, function(){
$(this).removeClass('buttonfullwidth_2');
});
}
if(buttonfullwidth_3 !== false) {
$(parentElement).hover(function(){
$(this).addClass('buttonfullwidth_3');
}, function(){
$(this).removeClass('buttonfullwidth_3');
});
}
if(buttonfullwidth_4 !== false) {
$(parentElement).hover(function(){
$(this).addClass('buttonfullwidth_4');
}, function(){
$(this).removeClass('buttonfullwidth_4');
});
}
if(buttonfullwidth !== false) {
$(parentElement).hover(function(){
$(this).addClass('buttonfullwidth');
}, function(){
$(this).removeClass('buttonfullwidth');
});
}
});
最佳答案
您需要使用 :hover
来完成这项工作的 CSS伪选择器
The
:hover
CSS pseudo-class matches when the user interacts with an element with a pointing device, it is generally triggered when the user hovers over an element with the mouse pointer.
例如,如果您希望此按钮在悬停时变为蓝色:
.myButton {
background-color: lightgreen;
}
.myButton:hover {
background-color: lightblue;
}
<button class="myButton">Hover this button</button>
请注意当元素处于悬停状态时我如何为该元素设置属性。
因此对于您的代码,您只需使用以下选择器:
buttonfullwidth
buttonfullwidth:hover
buttonfullwidth_1
buttonfullwidth_1:hover
buttonfullwidth_2
buttonfullwidth_2:hover
buttonfullwidth_3
buttonfullwidth_3:hover
buttonfullwidth_4
buttonfullwidth_4:hover
与我在示例中所做的方式相同。
关于javascript - 我怎样才能在js中制作更小的js代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51172246/