JS用特定ID替换内联背景图像

时间:2014-05-19 21:19:51

标签: javascript jquery html

从这个回答:https://stackoverflow.com/a/1775971/615477

var images = 'images/image_*.png';
var i = 1;
setInterval(function() {
    var path = images.replace('*', i);
    $('img').attr('src', path);
    i = i + 1;
    if (i == 6) i = 1;
}, 1000);

它将替换每个img

如何使它只替换特定ID中的内嵌背景图像,如下所示?

<div id="mr3" style="background:url(http://myweb.com/image1.jpg)"></div>

1 个答案:

答案 0 :(得分:2)

相当简单,与当前代码没有太大区别:

var images = 'images/image_*.png';
var i = 1;
setInterval(function() {
    var path = images.replace('*', i);
    $('#mr3').css('background-image', path);
    i = i + 1;
    if (i == 6) i = 1;
}, 1000);