開發中經常碰見元素使用background
或者background-imgae
等樣式表提供的屬性來展示圖片而不是img
使用標簽,在修改的時候就會發現弊端在需要動態修改圖片的時候沒有img.src
那樣順手,簡單的法子就是提取出元素的background
屬性,然后使用substr
字符傳截取獲取到的值,馬虎的思考一下這確實沒問題,但是真這樣做了之后就發現了一個問題(說的正式在下😄),不同瀏覽器下面同樣的代碼獲取到的結果不一致
反例
<div id='test' style='background:url(https://www.baidu.com/img/bd_logo1.png) 200px 100px;width:200px;height:100px'></div>
document.querSelector('#test').style.background
chrome
url("https://www.baidu.com/img/bd_logo1.png") 200px 100px
firefox
rgba(0, 0, 0, 0) url("https://www.baidu.com/img/bd_logo1.png") repeat scroll 200px 100px
其它內核手頭暫時沒有,沒有測試,使用傳統的substr
肯定是行不通了,接下來只有使用正則表達式
去解決了
如果使用style.backgroundImage
這兩瀏覽器獲取到的值就會是一樣的了
下面是使用正則表達式去獲取目標內容
第一步
匹配出url(xxxx)
使用/url\("?'?.*"?'?\)/g
let reg = /url\("?'?.*"?'?\)/g
'rgba(0, 0, 0, 0) url("https://www.baidu.com/img/bd_logo1.png") repeat scroll 200px 100px'.match(reg)
// ['url("https://www.baidu.com/img/bd_logo1.png")']
'url(https://www.baidu.com/img/bd_logo1.png)'.match(reg)
// ['url("https://www.baidu.com/img/bd_logo1.png")']
第二步
剔除不相關的內容,/"|'|url|\(|\)/g
let reg = /"|'|url|\(|\)/g
'url("https://www.baidu.com/img/bd_logo1.png")'.replace(reg,'')
// https://www.baidu.com/img/bd_logo1.png
最終
綜合前面的例子
function getBackgroundUrl(background){
let regBackgroundUrl = /url\("?'?.*"?'?\)/g;
let regReplace = /"|'|url|\(|\)/g;
return background.match(regBackgroundUrl)[0].replace(regReplace,'')
}
console.log(getBackgroundUrl('rgba(0, 0, 0, 0) url("https://www.baidu.com/img/bd_logo1.png") repeat scroll 200px 100px'))
// https://www.baidu.com/img/bd_logo1.png