最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to select the correct src from srcset with javascript - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论