adding @2x to src above certain resolution on none retina devices

回眸只為那壹抹淺笑 提交于 2019-12-20 07:22:10

问题


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');
});


来源:https://stackoverflow.com/questions/24302282/adding-2x-to-src-above-certain-resolution-on-none-retina-devices

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!