如何根据屏幕宽度更改图像路径? [英] How to change an image path based on screen width?

查看:369
本文介绍了如何根据屏幕宽度更改图像路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据窗口宽度更改从中读取图像的文件夹。

I'm trying to change the folder that my images are read from depending on the window width.

我有两个包含不同图像尺寸的文件夹我想知道是否有人可以根据屏幕宽度给我任何关于如何改变路径的建议。

I have two folders that contain the different image sizes and I'm wondering if anyone could give me any advice on how to change the path depending on the screens width.

如果屏幕是常规的< ; img> 看起来像

If the screen is regular the <img> would look like

<img src="images/620x410/image1.jpg" alt="">

如果屏幕处于平板电脑宽度,则会加载

and If the screen was in the tablet width it would load

<img src="images/310x205/images1.jpg" alt="">

310X205

image1.jpg
image2.jpg

620X410

image1.jpg
image2.jpg


推荐答案

您可以使用 $(窗口).width(); 确定窗口的大小,然后相应地设置图像的src:

You can use $(window).width(); to determine the size of the window, then set the src of the images accordingly:

$(function() {
  if($(window).width() <= 310) {
    $("img").each(function() {
      $(this).attr("src", $(this).attr("src").replace("images/620x410/", "images/310x205/"));
    });
  }
});

您还应该注意,如果我以< = 310px的大小启动浏览器窗口,那么将其调整到上面,您的图像仍然是较小的版本。如果需要,您可能需要考虑使用resize事件来解决这个问题:
http://api.jquery.com/resize/

You should also note that if I start my browser window at a size of <= 310px, then resize it to above that, your images will still be the smaller version. You might want to consider using the resize event to combat that if required: http://api.jquery.com/resize/

这篇关于如何根据屏幕宽度更改图像路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆