替换背景图像 URL 中的文本

Replace Text In Background Image URL

本文关键字:文本 URL 背景 图像 替换      更新时间:2023-09-26

简化,我有这个结构:

<div id="RelatedPosts1">
    <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div>
    <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-2.jpg)"></div>
    <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-3.jpg)"></div>
</div>

我希望将"s72-c"替换为"s320"。因此,更改图像的大小。

这是我用jQuery尝试的:

<!-- Let's replace low-res with a higher-res -->
$(".related-posts-thumb").text(function () {
    return $(this).text().replace("s72-c", "s320"); 
});

我猜这不起作用,因为图像 URL 不在元素的"内部"。所以我不确定如何达到我想要的效果。我不是javascript/jQuery专家,我还没有看到任何与我正在尝试做的事情类似的示例。

不太确定何时触发它,所以我只是

点击一下...
 $('.related-posts-thumb').each(function() {
     $(this).attr("style", $(this).attr("style").replace("s72-c", "s320"));
 });

JSFiddle示例(点击背景):

http://jsfiddle.net/wdc6ydtk/1/

您可以将 .css() 方法与函数参数选项一起使用

$('.related-posts-thumb').css("background-image",function(idx,current){
    return current.replace('s72-c','s320');         
 });