为什么这个Javascript在IE中不起作用

时间:2013-07-03 10:46:04

标签: javascript html internet-explorer

我在Javascript中有一段代码可以在Chrome和Firefox中运行,但在IE中不起作用。该代码应该在鼠标悬停某些div时更改CSS背景图像,并在鼠标移出时删除背景图像。

使用Javascript:

$(document).ready(function() {
    $('.expositores1').hover(function() {
        $('.expositores1').css('background-image', 'url(/wp-content/themes/kallyas/images/mapa/piso0/inter_piso0_r5_c2_f4.jpg)', 'background-repeat', 'no-repeat');
        $('.expositores2').css('background-image', 'url(/wp-content/themes/kallyas/images/mapa/piso0/inter_piso0_r12_c2_f2.jpg)', 'background-repeat', 'no-repeat');
        $('.expositores3').css('background-image', 'url(/wp-content/themes/kallyas/images/mapa/piso0/inter_piso0_r12_c4_f2.jpg)', 'background-repeat', 'no-repeat');
        $('.expositores4').css('background-image', 'url(/wp-content/themes/kallyas/images/mapa/piso0/inter_piso0_r14_c3_f2.jpg)', 'background-repeat', 'no-repeat');
    });
    $('.expositores1').mouseout(function() {
        $('.expositores1').css('background-image', 'none');
        $('.expositores2').css('background-image', 'none');
        $('.expositores3').css('background-image', 'none');
        $('.expositores4').css('background-image', 'none');
    });
});

HTML:

<div class="expositores1"></div>
<div class="expositores2"></div>
<div class="expositores3"></div>
<div class="expositores4"></div>

CSS:

.expositores1{
    position: absolute;
    width: 306px;
    height: 122px;
    margin-left: 11px;
    margin-top: 146px;
}
.expositores2{
    position: absolute;
    width: 81px;
    height: 127px;
    margin-left: 11px;
    margin-top: 268px;
}
.expositores3{
    position: absolute;
    width: 185px;
    height: 127px;
    margin-left: 132px;
    margin-top: 268px;
}
.expositores4{
    position: absolute;
    width: 40px;
    height: 90px;
    margin-left: 92px;
    margin-top: 304px;
}

任何人都可以提供帮助?为什么它在Chrome和Firefox中有效但在IE中不起作用?

此致 雨果

2 个答案:

答案 0 :(得分:6)

您错误地使用了jQuery css()函数。

如果您只想设置一个属性,请使用:.css('prop', 'value')

如果您需要一次设置多个属性,则必须传递object。在你的情况下:

.css({
     'background-image':'url(/wp-content/themes/kallyas/images/mapa/piso0/inter_piso0_r5_c2_f4.jpg)',
     'background-repeat':'no-repeat'
    });

另外,作为@Miro Markarian pointed out,你真的应该依靠CSS :hover指令来实现它,而不是JavaScript。

答案 1 :(得分:3)

使用css hover选择器可以更轻松地完成此操作.. CSS已经实现了..

你有点重新发明轮子。

只需将hover添加到该css元素的hover选择器时添加任何内容:

.expositores1{
    position: absolute;
    width: 306px;
    height: 122px;
    margin-left: 11px;
    margin-top: 146px;
    background-color: #F00;
}
.expositores1:hover {
    background-color: #00F;
}

最好将鼠标移出后,浏览器会切换回普通选择器。 没有必要为你做javascript。

以下是我为您创建的JsFiddle

相关问题