简体   繁体   English

根据屏幕分辨率动态更改图像

[英]Dynamically change image depending on screen resolution

I have a section with a fullscreen background image that is loaded via a JavaScript data-attribute. 我有一个带有全屏背景图片的部分,该背景图片是通过JavaScript数据属性加载的。 As this is a responsive site, the same background image (1920 x 1080px) is scaled up and down depending on the screen size, which is not very performance-friendly, eg on mobile phones with smaller screen sizes. 由于这是一个响应式站点,因此根据屏幕尺寸来放大和缩小相同的背景图像(1920 x 1080px),这并不是非常友好的性能,例如在屏幕较小的手机上。

HTML: HTML:

<!-- BEGIN PAGE TITLE -->
<section id="page-title" class="page-title-lg" data-bg-img="nature/full-20.jpg">
  <div class="container">
    <div class="page-title-wrapper">
      <div class="page-title-txt">
        <h1>Large Page Title</h1>
      </div>
    </div>
  </div>
</section>
<!-- END PAGE TITLE -->

JS: JS:

// Image Background 
$('[data-bg-img]').each(function() {
      var dataImg = $(this).attr('data-bg-img');
      $(this).css('background-image', 'url(assets/img/' + dataImg + ')');
 });

Is there a way to dynamically detect the window size and load the appropriate image via different data-attributes (eg 2560 x 1440, 1920 x 1440, 1280 x 800, 640 x 960, etc.) ? 是否有办法动态检测窗口大小并通过不同的数据属性(例如2560 x 1440、1920 x 1440、1280 x 800、640 x 960等)加载适当的图像?

If have three different images for say tablet, desktop, and mobile devices you could create a simple system to automatically choose the correct image to load. 如果说平板电脑,台式机和移动设备具有三个不同的图像,则可以创建一个简单的系统来自动选择要加载的正确图像。

<section id="page-title" class="page-title-lg" data-bg data-bg-img-desktop="nature/full-20.jpg" data-bg-img-tablet="nature/full-20.jpg" data-bg-img-mobile="nature/full-20.jpg"></section>

Notice the four attributes: data-bg data-bg-img-desktop, data-bg-img-tablet, data-bg-img-mobile. 请注意以下四个属性:data-bg data-bg-img-desktop,data-bg-img-tablet,data-bg-img-mobile。

When the page loads, get the screen width and load the image that is closest to the screen size: 页面加载时,获取屏幕宽度并加载最接近屏幕尺寸的图像:

<script type="text/javascript">

var imageBgs = document.querySelectorAll('[data-bg]');
var screenWidth = window.innerWidth;

for(var i=0; i<imageBgs.length; i++) {
    if( screenWidth < 768 ){
        // Load mobile image
        imageBgs[i].style.backgroundImage = 'url('+imageBgs[i].getAttribute('data-bg-img-mobile')+')';
    } else if( screenWidth >= 768 && screenWidth <= 1024 ) {
        // Ipad
        imageBgs[i].style.backgroundImage = 'url('+imageBgs[i].getAttribute('data-bg-img-tablet')+')';
    } else {
        // desktop image
        imageBgs[i].style.backgroundImage = 'url('+imageBgs[i].getAttribute('data-bg-img-desktop')+')';
    }
}

</script>

Is there a reason you can't change the CSS directly? 您是否有理由不能直接更改CSS?

There are a few ways you could go about this. 有几种方法可以解决此问题。 One way would be to listen to the resize event, and update all images accordingly. 一种方法是监听resize事件,并相应地更新所有图像。 However, you can also use jquery to create your media queries for each element during page load, and just let the browser handle switching everything out. 但是,您也可以使用jquery在页面加载期间为每个元素创建媒体查询,并让浏览器处理所有内容的切换。

Here's a fiddle illustrating how to do that: https://jsfiddle.net/czr41bqp/ 这是说明如何做到的小提琴: https : //jsfiddle.net/czr41bqp/

Essentially you would add a style in for each screen size you want to switch at and create your style element here and append it to your header. 本质上,您将为每个要切换的屏幕尺寸添加样式,并在此处创建style元素并将其附加到标题中。 Of course, this requires that you have pre-generated all versions of the images and that the sizes are consistent with each image. 当然,这需要您预先生成图像的所有版本,并且大小与每个图像都一致。

$(function() {
  //define a template with all media queries we want to target
  var mediaQueryTemplate = '\
    @media screen and (min-width:350px) { \
        #{{ID}} { background-image: url({{BASE_URL}}/350x150) } \
    } \
    @media screen and (min-width:640px) { \
        #{{ID}} { background-image: url({{BASE_URL}}/640x960) } \
    } \
    @media screen and (min-width:1280px) { \
        #{{ID}} { background-image: url({{BASE_URL}}/1280x800) } \
    } \
    @media screen and (min-width:1280px) { \
        #{{ID}} { background-image: url({{BASE_URL}}/1280x800) } \
    } \
    @media screen and (min-width:1920px) { \
        #{{ID}} { background-image: url({{BASE_URL}}/1920x1440) } \
    } \
    @media screen and (min-width:2560px) { \
        #{{ID}} { background-image: url({{BASE_URL}}/2560x1440) } \
    } \
  ';

  var $style = $('<style>');
  $style.appendTo('head');

  $('[data-bg-img]').each(function() {
    //generate all media queries from the template for each image and add them to the style tag

    var dataImg = $(this).attr('data-bg-img');
    var mediaQueries = mediaQueryTemplate.replace(/{{ID}}/g, this.id).replace(/{{BASE_URL}}/g, dataImg);

    $style.text($style.text() + mediaQueries);
  });
});

One approach would be to leave the "src" attribute blank and then assign it depending on the screen width. 一种方法是将“ src”属性保留为空白,然后根据屏幕宽度进行分配。

windowSize = $("window").width();

if(windowSize >= 1000){
$("img").attr("src","bigFile.png")
}
if(windowSize <= 999 && windowSize >= 500){
$("img").attr("src","mediumFile.png")
}
if(windowSize < 499){
$("img").attr("src","mobileFile.png")
}

Alternatively you could use something like: 另外,您可以使用类似:

if(windowSize >= 1000){
    $("imageContainer").html("<img src="bigFile">);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM