我想替換CSS('background-image')路徑。如何替換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」或「文件」),我只想替換URL中的fileName。
使用正則表達式可以更容易嗎? – Pietu1998
因爲我知道你可以在ff中使用帶引號和不帶引號的url。嘗試改變它,看看會發生什麼! – Homam
@ Pietu1998 - 如何? – Atara