adding @2x to src above certain resolution on none

2019-03-04 08:27发布

问题:

I use retinaJS on my site to serve @2x images on retina devices.

I would also like to be able to use jQuery to server @2x images on none retina - large screen desktop devices. So if the screen resolution is above 1330px then I want to be able to add @2x to the end of the filename directly before the file suffix/extension.

Can someone suggest how I might do this?

My theory was to find all images within a target DIV (e.g. .bodycontent) and then count back 4 characters from the attribute src and add in @2x to the src

e.g.

example.jpg becomes example@2c.jpg and chickens.png becomes chickens@2x.png

This of course only works on files with 3 leter extensions - e.g. png / jpg - but that is OK as I never call files JPEG for example...

I need the code to apply to ALL images found in the target DIV.

Any help?

Cheers

This function is called on every resize to check it the @2x needs to be applied - how can I add some code to check to see if @2x is already included in the attr src and then not perform this if it is already @2x?

回答1:

This should do it, regardless of the extension length, so long as the .xxx is the final part of the image URL:

$('.bodycontent img').prop('src', function(_, src) {
    src = src.replace(/@2x\./, '.');         // strip if it's already there
    return src.replace(/(\.\w+$)/, '@2x$1');
});


标签: jquery retina