通过JavaScript更改后台网址路径

时间:2018-04-11 09:37:12

标签: javascript jquery

使用$('section').css('background');

获取部分的背景

我在控制台中得到的结果如下:

rgb(13,25,73)url(" http://website.com/image_01_closed.jpg")no-repeat scroll 50%100%/包含padding-box border-box

想知道如何将网址路径从_closed.jpg更改为_opened.jpg? 有很多部分,所以想要为任何带有_closed的图像更改它。

3 个答案:

答案 0 :(得分:0)

你可以这样试试,

var el = document.getElementById("section_id").style.backgroundImage;
    if(el == "url(close.jpg)") { // full value is provided
       el.style.backgroundImage = "url(/link/open.png)"; // change it
}

答案 1 :(得分:0)

使用此代码找到工作解决方案:

var url = $('section').css('background-image');
var res = url.replace("_closed", "_opened");
$('section').css('background-image',res);

感谢您的帮助。

答案 2 :(得分:0)



$(document).ready(function(){
$('#btn').click(function(){
$('div').toggleClass('close')
})
})

.open{
height: 200px;
width:200px;
background-image: url("http://s5.tinypic.com/35jbaqq_th.jpg");
background-repeat: no-repeat;
background-color: #cccccc;
background-position: center;

}
.close{
height: 200px;
width:200px;
background-image: url("http://s6.tinypic.com/vg04ft_th.jpg");
background-repeat: no-repeat;
background-color: #fff;
background-position: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn'>change BG</button>
<br/>
<br/>
<div class='open'>
Content
</div>
<br/>
<div class='open'>
Content
</div>
&#13;
&#13;
&#13;

相关问题