1

:hover在 CSS 样式表文件中声明了一个样式定义:

.myclass:hover {
    border-color: red;
    background-image: url('http://goo.gl/zdLfy');
}

现在,在给定的条件下,我想更改background-image此悬停样式。

我不知道如何使用 JavaScript / jQuery 做到这一点。这可能吗?如何?

4

4 回答 4

2

您可以在之前的声明上添加新的样式标签级联。假设在 head 标签中的 css

$('head').append('<style>#element:hover {/
    background-image: url("http://new.image/url");/
}/
<style>');
于 2013-04-30T23:15:31.540 回答
1
$('#element').hover(function() {
//on hover
    if(condition === true) {
        $(this).addClass('newBGImage');
    }
}, function() {
//when hover ends
    if($(this).hasClass('newBGImage')) {
        $(this).removeClass('newBGImage');
    }
});
于 2013-04-30T23:08:55.730 回答
1

让你的 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 中它们所属的位置

于 2013-04-30T23:25:18.950 回答
0

您想添加一个具有新背景的类,然后在悬停时使用类似

$(this).addClass("YourClassName");

然后请假

$(this).removeClass("YourClassName");
于 2013-04-30T23:09:19.977 回答