我想替换 css('background-image') 路径。
问题:
对于同一个变量oldBgImg = this.element.css('background-image')
火狐回归——
"url("http://mySite/images/file1.png")"
但 Chrome不带引号返回它:
"url(http://mySite/images/file1.png)"
这是我使用的解决方案。你能帮我简化一下吗?
var oldBgImg = this.element.css('background-image');
// => FF: "url("http://mySite/images/file1.png")"
// Chrome: "url(http://mySite/images/file1.png)"
// According to http://www.w3.org/TR/CSS2/syndata.html#value-def-uri :
// quotes are optional, so Chrome does not use them, but FF does . . .
var n1 = oldBgImg.lastIndexOf("("); n1 += 1; // now points to the char after the "("
var n2 = oldBgImg.lastIndexOf(")"); n2 -= 1; // now points to the char before the ")"
var c1 = oldBgImg.substring(n1, n1 + 1); // test the first Char after the "("
var c2 = oldBgImg.substring(n2, n2 + 1); // test the first Char after the "("
if ( (c1 == "\"") || (c1 == "\'") ) { n1 += 1; }
if ( (c2 == "\"") || (c2 == "\'") ) { n2 -= 1; }
var oldBgImgPath = oldBgImg.substring(n1, n2 + 1); // [ (" ] .. [ ") ]
var n = oldBgImgPath.lastIndexOf("/");
var newBgImgPath = oldBgImgPath.substring(0, n + 1) + "file2.gif";
// if needed, should also add :
// var path = encodeURI(newBgImgPath);
this.element.css('background-image', 'url(' + newBgImgPath + ')');
笔记:
根据http://www.w3.org/TR/CSS2/syndata.html#value-def-uri 一个可以使用单引号或双引号或无引号符号
我正在寻找一个通用解决方案,也适用于相对路径(没有“http”或“file”),我只想替换 URL 中的文件名。