1

我想替换 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 + ')');

笔记:

  1. 根据http://www.w3.org/TR/CSS2/syndata.html#value-def-uri 一个可以使用单引号或双引号或无引号符号

  2. 我正在寻找一个通用解决方案,也适用于相对路径(没有“http”或“file”),我只想替换 URL 中的文件名。

4

3 回答 3

1

这是一个如何使用正则表达式的示例。-现场演示

表达方式:

("?)(http:.*?)\1\)

比赛

url = 'url("http://mySite/images/file1.png")'.match(/("?)(http:.*?)\1\)/)[2];

然后,您可以重建您的财产。

$(this).css( 'background-image', 'url("' + url + "')" );

这应该适用于所有浏览器。

于 2013-07-28T11:30:21.450 回答
1

我用正则表达式做到了。我使用这段代码:

var re = /url\(['"]?(.+?)[^\/]+['"]?\)/;
var regs = re.exec(oldBgImg);
var newBgImgPath = regs[1] + "file2.png";

JSFiddle

我将解释RE。

  1. 它以 开头/,这将表明它是一个 RE。
  2. 然后是url\(. 它与文本匹配url((被转义,因为它是保留字符。
  3. 然后有['"]?['"]匹配'or"?使其成为可选。
  4. A(启动一个可以引用的 RE 组。
  5. In.+? .匹配除换行符以外的所有字符。A+表示必须至少有 1 个或更多。最后,a?使+非贪婪,因此它匹配尽可能少的字符,但仍尝试匹配整个 RE。
  6. A)结束该组。
  7. [^\/]匹配任何非/字符。然后+又是一个。它?后面没有,因为我们想/ 从末尾匹配尽可能多的非字符(文件名)。
  8. 最后,另一个可选的引号,一个转义)的右括号url(...)和一个/结束 RE。

现在re.exec(oldBgImg)返回一个数组,其中第一个元素是整个匹配的字符串,下一个元素是匹配的 RE 组(由()括号创建)。然后我可以取regs[1],这是第一个匹配的并包含路径名。

于 2013-07-28T11:43:32.697 回答
0

你可以用这样的东西替换引号oldBgImg

oldBgImg = oldBgImg.replace(/\"/g, "");

这样,无论浏览器检索到 URL,URL 总是相同的。

于 2013-07-28T11:42:46.027 回答