用jQuery设置css背景图像

时间:2014-02-14 21:52:25

标签: jquery

单击标题时尝试在两个图像之间切换。首先,我甚至无法让他们展示。有什么想法吗?

<h2 class="expand" id="content-1" style="cursor:pointer;" value="One">Click to expand One</h2>
<h2 class="expand" id="content-2" style="cursor:pointer;" value="Two">Click to expand Two</h2>

到目前为止尝试但没有。

 $('.expand').on('click', function() {
              if($(this).text().indexOf('expand') >0 )
              $(this).text('Click to collapse ' + $(this).attr("value"));
                $('.expand').css('background-image', 'url(' + img/arrow-up.gif + ')');
               else
                   $(this).text('Click to expand ' + $(this).attr("value"));
                 $('.expand').css('background-image', 'url(' + img/down-up.gif + ')');  
            });

$(this).text('Click to collapse ' + $(this).attr("value") + $(this).css...);

2 个答案:

答案 0 :(得分:1)

最简单的选择是切换类名并在CSS中定义图像。

$('.expand').toggleClass('someClass')


.someClass {
     background-image:url(...);
}

答案 1 :(得分:0)

此:

 $('.expand').css('background-image', 'url(' + img/arrow-up.gif + ')');

可能应该这样:

 $('.expand').css('background-image', 'url("img/arrow-up.gif")');

但我是第二个Diaodeus并且这应该在CSS中指定,你的jQuery只是交换类名。我也将你的图像变成一个精灵,所以它只是一个图像。