1

我有一些 jquery 代码可以在单击以显示另一个按钮时更改我的按钮;(它们是背景按钮图像)

但我不能让它显示背景图像。我可以改变它的颜色,但不知道如何添加背景图像。

换人解释我需要在哪里更改代码

$('.chartme-btn-main').click(function(){
    if($(this).attr('att') == 0){
          $(this).css('background', '');
        $(this).attr('att',1);
    } else {
          $(this).css('background', 'yellow');
        $(this).attr('att',0);
    }
  });

任何帮助都会很棒!!!!

4

4 回答 4

0

我会创建一个精灵图像并更改它background-position
这种方法的好处是无需等待加载新图像的请求

现场演示

CSS:

.chartme-btn-main{
  background:url('images/buttonSprite.jpg');
}

.chartme-btn-main.active{
  background-position: 0px -210px;
}

jQuery:

$('.chartme-btn-main').click(function(){
    $(this).toggleClass('active');
});
于 2013-09-10T13:57:07.497 回答
0

尝试这个:

var imgUrl = "http://silverspaceship.com/static/shot_1.png";
$(this).css('background', 'url(' + imgUrl + ')');
于 2015-02-12T20:35:13.657 回答
0

尝试这个:

$('.chartme-btn-main').click(function() {
    $(this)
        .css('background', $(this).data('att') == 0 
            ? 'none' 
            : 'yellow url(yourimagepath)')
        .data('att', $(this).data('att') == 0 
            ? 1 
            : 0);
});
于 2013-09-10T13:54:05.547 回答
0

http://jsfiddle.net/wvLYd

var imgUrl = "http://silverspaceship.com/static/shot_1.png";
$(this).css('background', 'url('+imgUrl+')');

更新

http://jsfiddle.net/wvLYd/2/

更好的解决方案:@Paul O'Brien 的“不等待加载新图像的请求”

于 2013-09-10T13:56:12.830 回答