在CSS中我有background-image: url(folder/bg.jpg);
。
为此,JQuery的css("background-image")
回报url(http://www.example.com/folder/bg.jpg)
,
,但我只需要folder/bg.jpg
。
我正在寻找一个正则表达式来解决这个问题。
在CSS中我有background-image: url(folder/bg.jpg);
。
为此,JQuery的css("background-image")
回报url(http://www.example.com/folder/bg.jpg)
,
,但我只需要folder/bg.jpg
。
我正在寻找一个正则表达式来解决这个问题。
尝试使用String.prototype.split()
与RegExp
/\//
,Array.prototype.join()
,String.prototype.slice()
$("div").html(
$("div").css("backgroundImage").split(/\//)
.slice(-2).join("/").slice(0, -1)
)
div {
background-image: url(http://www.example.com/folder/bg.jpg)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div></div>
当然,路径总是不同的,这只是一个例子。 – tom
@tom查看更新后的帖子 – guest271314
你肯定有更好的替换window.location.hostname在返回的字符串,但仍然不会是在CSS属性中设置的路径 –
由于jQuery将返回的绝对路径,你将永远无法确定没有字符串操作了解的相对路径是什么删除给定如何嵌套您的网页可能在您的目录层次结构。我会建议字符串替换正则表达式。见下面的plnkr。
$("div").click(function() {
var bg = $(this).css('background-image');
bg = bg.replace('url(http://run.plnkr.co/cybkjF7HN9sYH3oS/','').replace(')','');
alert(bg);
});
我知道这是不是所有的情况下最好的正则表达式,但你明白了吧。
/* Explaining:
/regex here/
[^\/]+ ---> will match anything before a/(https:)
\/\/ ---> the // after https:
[^\/]+ ---> will match anything before/(www.example.com)
\/ ---> will match/
(.*) ---> the rest of url (that you want)
So, you need to get the [1] index of the returned array.
*/
"http://www.example.com/folder/bg.jpg".match(/[^\/]+\/\/[^\/]+\/(.*)/)[1]
将返回: “文件夹/ bg.jpg”
为什么你需要的CSS样式计算返回相对路径? –
+1 @A。狼。除此之外,如果你想为其他元素重用背景图片,绝对可以用绝对路径来实现。 –
它应该是计算图像主色的函数的输入参数。当页面加载时,具有背景图像的div会根据背景图像接收背景颜色。 – tom