Jquery - 将src和srcset的.jpg更改为.gif

时间:2018-03-09 17:27:04

标签: jquery replace

所以我想能够在父行悬停时将.jpg转换为.gif时,能够获得wordpress的响应图像(在srcset中指定)。

我能够让它适用于src但不适用于srcset。对于jquery来说,我是新手。

$j(".featured-row").mouseenter(
    function() {
        var src = $j("img", this).attr("src");
        var srcset = $j("img", this).attr("srcset");
        $j("img", this).attr("src", src.replace(/\.jpg$/i, ".gif"));
        $j("img", this).attr("srcset", srcset.replace(/\.jpg$/i, ".gif"));
    }),
$j(".featured-row").mouseleave(function() {
    var src = $j("img", this).attr("src");
    var srcset = $j("img", this).attr("srcset");
    $j("img", this).attr("src", src.replace(/\.gif$/i, ".jpg"));
    $j("img", this).attr("srcset", srcset.replace(/\.gif$/i, ".jpg"));
});`

正如我所提到的,替换src的部分工作正常。只是不是srcset。

下面给出了一个示例img url

<img width="1060" height="600" src="http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2.jpg" class="vc_single_image-img attachment-full" alt="" srcset="http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2.jpg 1060w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-300x170.jpg 300w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-768x435.jpg 768w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-1024x580.jpg 1024w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-700x396.jpg 700w" sizes="(max-width: 1060px) 100vw, 1060px">

1 个答案:

答案 0 :(得分:1)

srcset属性包含:

srcset="http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2.jpg 1060w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-300x170.jpg 300w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-768x435.jpg 768w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-1024x580.jpg 1024w, http://adwaitpawar.com/niyo/wp-content/uploads/2018/03/n15-2-700x396.jpg 700w"

这些包含多个.jpg,因此您应添加全局修饰符/g

此外,您的正则表达式会将.jpg$与美元符号匹配,该符号将与该行末尾的.jpg匹配。

您可以更新此行:

srcset.replace(/\.jpg$/i, ".gif")

srcset.replace(/\.jpg/gi, ".gif")

并且

srcset.replace(/\.gif$/i, ".jpg")

srcset.replace(/\.gif/ig, ".jpg")