admin管理员组

文章数量:1419168

I have a srcset on my page

<img src="bg__x-large.png" srcset="bg__small.png 900w, bg__med.png 1200w, bg__large.png 1920w">

This is used by a parallax script, which right now just reads the src attribute

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

to set this as the background image.

How can I read the correct src from the srcset with jquery?

I have a srcset on my page

<img src="bg__x-large.png" srcset="bg__small.png 900w, bg__med.png 1200w, bg__large.png 1920w">

This is used by a parallax script, which right now just reads the src attribute

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

to set this as the background image.

How can I read the correct src from the srcset with jquery?

Share Improve this question asked Jun 21, 2016 at 8:50 tommuellertommueller 2,4963 gold badges33 silver badges49 bronze badges 1
  • @newnoise there are multiple images in srcset which one you want to get; ? – Mairaj Ahmad Commented Jun 21, 2016 at 8:59
Add a ment  | 

1 Answer 1

Reset to default 6

Use the .currentSrc property (as opposed to .src) of the image to determine the active "src":

jq: $(this).prop('currentSrc')

vanilla: this.currentSrc

see mdc's HTMLMediaElement.currentSrc docs for more info.

本文标签: jqueryHow to select the correct src from srcset with javascriptStack Overflow