我:hover
在 CSS 样式表文件中声明了一个样式定义:
.myclass:hover {
border-color: red;
background-image: url('http://goo.gl/zdLfy');
}
现在,在给定的条件下,我想更改background-image
此悬停样式。
我不知道如何使用 JavaScript / jQuery 做到这一点。这可能吗?如何?
我:hover
在 CSS 样式表文件中声明了一个样式定义:
.myclass:hover {
border-color: red;
background-image: url('http://goo.gl/zdLfy');
}
现在,在给定的条件下,我想更改background-image
此悬停样式。
我不知道如何使用 JavaScript / jQuery 做到这一点。这可能吗?如何?
您可以在之前的声明上添加新的样式标签级联。假设在 head 标签中的 css
$('head').append('<style>#element:hover {/
background-image: url("http://new.image/url");/
}/
<style>');
$('#element').hover(function() {
//on hover
if(condition === true) {
$(this).addClass('newBGImage');
}
}, function() {
//when hover ends
if($(this).hasClass('newBGImage')) {
$(this).removeClass('newBGImage');
}
});
让你的 CSS 变成这样:
.myclass:hover {
border-color: red;
background-image: url('http://goo.gl/zdLfy');
}
.specialCondition:hover {
background-image: url('http://anotherURL');
}
然后,对于这种特殊情况,请执行以下操作:
$('.myclass').addClass('specialCondition');
当特殊条件不再存在时,删除该类:
$('.myclass').removeClass('specialCondition');
这样,您可以将背景网址保存在 CSS 中它们所属的位置
您想添加一个具有新背景的类,然后在悬停时使用类似
$(this).addClass("YourClassName");
然后请假
$(this).removeClass("YourClassName");