jquery - 使用 jQuery 选择和更改特定的背景图像

标签 jquery css background-image

我正在尝试从多元素背景图像属性中选择某个值,例如

background-image: url(a.jpg), url(b.jpg), url(c.jpg)  

使用单个 jQuery 表达式。

目前的解决方案是用element.css('background-image')替换完整的属性。

我的目的是使用户能够为第二个 url() 循环浏览一组背景图像,而其他背景图像保持不变。有没有比更换整条线更简单的方法?我对正则表达式替换不是很有信心,非常感谢任何形式的帮助。

最佳答案

不,没有。即使有多个背景图像,您仍然只有一个属性 background-image。需要自己把字符串值整理出来递回去。像下面这样的东西就可以了。

jsFiddle

<div id="showcase"></div>
<button class="changeBG firstBG">change first bg image</button>
<button class="changeBG secondBG">change second bg image</button>
<button class="changeBG thirdBG">change third bg image</button>

var backgrounds = [
    ["url11", "url12", "url13"],
    ["url21", "url22", "url23"],
    ["url31", "url32", "url33"],
];
$('#showcase').data('currentBGs', [0,0,0]);
$('.changeBG').on('click',function(){
    var $button = $(this),
        whichButton,
        whichBGnum,
        bgLength,
        currentBGs,
        bgString,
        bg0,
        bg1,
        bg2;

    if( $button.hasClass('firstBG') ){
        whichButton = 0;
    }else if( $button.hasClass('secondBG') ){
        whichButton = 1;
    }else if( $button.hasClass('thirdBG') ){
        whichButton = 2;
    }

    currentBGs = $('#showcase').data('currentBGs');
    currentBGnum = currentBGs[whichButton];
    bgLength = backgrounds[whichButton].length;

    currentBGnum = ( currentBGnum + 1 ) % bgLength;
    currentBGs[whichButton] = currentBGnum;
    bg0 =  backgrounds[0][ currentBGs[0] ];
    bg1 =  backgrounds[1][ currentBGs[1] ];
    bg2 =  backgrounds[2][ currentBGs[2] ];
    bgString = 'url(' + bg0 + '), url(' + bg1 + '), url(' + bg2 + ')';

    $('#showcase').data('currentBGs', currentBGs)
        .css('background-image', bgString);  
});

此代码不打算优化,但可读性强。示例图片很傻,它们只是我打开的任何浏览器窗口。

  • 保留所有图片的 JS 数组。这是一个多维数组,第一层代表背景的每个部分,第二层是该背景的每个选项。
  • 写下背景的当前状态,这里我们只是.data()
  • 找出点击了哪个按钮
  • 获取显示器上的当前状态
  • 循环适当的计数器
  • 获取新背景
  • 使用数据和新背景更新显示状态。

关于jquery - 使用 jQuery 选择和更改特定的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9145220/

相关文章:

javascript - 查找两个单独的 JavaScript 对象之间的重复值?

php - 文本输入更改值和即时检查

html - 为什么 bootstrap 的 `table-fixed` 不能使我的表格变成滚动表格?

css - 无法在 codeigniter 中使用 css 背景加载给定的 url

css - 如何将 CSS 背景图像保持在所有 div(面包屑箭头)之上?

javascript - 在提交调试之前显示表单值

jquery - 如何检查div是否有脚本?

javascript - 使用 JavaScript 显示隐藏的 div

css - 如何轻松增加 Twitter Bootstrap css 系统中所有表单元素的字体大小?

html - 使用 CSS 在带有填充的渐变上叠加图像