根据视口宽度更改图像源 [英] Change image source based on viewport width

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

问题描述

<script type="text/javascript">
  $(window).resize(function(){
  var width = $(window).width(); 

   if (width < 361) {
      $(".infograph-image").attr("src","/images/infographicHowMobile.png");
   }
 }); 
</script>

我希望根据视口宽度大小更改给定图像的图像源. 如果视口宽度尺寸小于或等于360,请更改为图像的移动版本.

I wish to change the image source of a given image, based on the viewport width size. If the viewport width size is 360 or less, change to a mobile version of the image.

我有两个简单的问题:

1) 我们如何才能做到:a)检测窗口的大小并准备好文档?

1) How can we do both: a) detect windows resize AND document ready ?

这,我相信我得到了

我需要将其更改为一个函数. 然后在加载时调用它;

I need to change that into a function. Then call it on load;

checkResponsive();

然后绑定事件侦听器:

$(window).resize(checkResponsive);

2) 我们有几个需要移动版本的图像,应该将其转换为功能吗?还是几个if可能起作用?

2) We have several images that need to have a mobile version, should this be converted to a function ? Or several ifs may work ?

能否请您从这两个问题开始.

Can you please give me a kick-off start on those two questions please.

推荐答案

创建一个单独的函数,并在两个事件上调用它们. 因此,例如,如下创建函数mobileImg():

Create a seperate function and call them on both events. So, for example, create the function mobileImg() like this:

function mobileImg(targetClass, imageSrc) {
    var width = window.innerWidth; // No need for jQuery here, raw JS can do this

    if(width < 361) {
        $(targetClass).attr("src", imageSrc);
    }
}

然后在两个事件上都调用它.

And then call this on both events.

$(document).ready(mobileImg(".infograph-image", "/images/infographicHowMobile.png"));
$(window).resize(mobileImg(".infograph-image", "/images/infographicHowMobile.png"));

然后您可以根据需要使用任意参数调用mobileImg方法. 如果您真的想使其干净,还可以检查传递的元素和图像是否完全存在,并在需要时使用备用.

You can then call the mobileImg method as much as you want and with whatever params. If you really want to make it clean, also add a check if the passed element and image exist at all and use fallbacks where needed.

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

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