Javascript 更改图片标记中的srcset属性值

Javascript 更改图片标记中的srcset属性值,javascript,jquery,html,Javascript,Jquery,Html,我想检查源媒体属性是否为450px,根据结果,我必须更改srscet属性 提前感谢您可以使用javascript并获取其宽度: <picture class="pic_test"> <source media="(min-width:450px)" srcset="1190.jpg"> <source media="(min-width:900px)" srcset="120.jpg"> <img src="new.jpg" alt="Flo

我想检查源媒体属性是否为450px,根据结果,我必须更改srscet属性

提前感谢

您可以使用javascript并获取其宽度:

<picture class="pic_test">
  <source media="(min-width:450px)" srcset="1190.jpg">
  <source media="(min-width:900px)" srcset="120.jpg">
  <img src="new.jpg" alt="Flowers" style="width:auto;">
</picture>
你是说

var image = new Image();
image.src = $("source#id??").attr("srcset");
image.onload = function() {
    var width = image.width;
    if(width == 450){
        //do stuff
    } else {
       //do other stuff
    }
}
如果您需要特定来源:

var $pic = $("picture"), $source=$pic.find("source"), media=$source.attr("media");
if (media.indexOf("450px")!=-1) $source.attr("srcset","small.jpg");
或直接使用attr:

$("picture").find("source").each(function() {
  if ($(this).attr("media").indexOf("450px")!=-1) {
    $(this).attr("srcset","small.jpg");
  }
});

您可能需要转义一些-或:

您只需使用选择器并更改srcset属性,如下所示:

$('[media="(min-width:450px)"]').attr("srcset","small.jpg");

这将比类似
$(“source:eq(0)”)
更好地为您服务,以防源属性的顺序发生更改。

继续更改,什么阻止了您?我们无法为源属性添加任何类/id。那么,我们如何检查条件并更改特定的源标记
$(“source#id??)
可以是
$(“source:eq(0)”)
$(“source:eq(1)”)
。在设置响应的srcstungjan之前,您应该分配事件处理程序。它正在工作。但它正在更新所有srcset
$('[media^="(min-width:450px)"]').attr('srcset' , 'newSrcSet.jpg')