简体   繁体   中英

How to change the image components according to the screen size?

I have a study case:

I have an image wrapped in an intro div for the desktop size like this:

<div class="intro">
            <img id="gambar" src="assets/images/image-intro-desktop.jpg" alt="">
        </div>

then when entering the mobile file size the img tag will change to:

<img id="gambar" src="assets/images/image-intro-mobile.jpg" alt="">

So the question is how do I change the component, what js code should I use??

You can do this using css

<style>
  .intro{
    content:url("assets/images/image-intro-desktop.jpg");
  }

  @media only screen and (max-width: 600px) {
    .intro{
       content:url("assets/images/image-intro-mobile.jpg");
    }
  }
  </style>

  <img class="intro"/>

You would need to add two event listeners for the resize and load events, check the window width if it's smaller than your desired breakpoint to change the image source. Otherwise reset the source back to the original.

 document.addEventListener( 'resize', changeImageSrc() ); document.addEventListener( 'load', changeImageSrc() ); function changeImageSrc() { var init_img_src = document.getElementById('gambar').src; // Change 600 to your breakpoint if( window.innerWidth < 600 ) { document.getElementById('gambar').src = 'https://via.placeholder.com/250'; } else { document.getElementById('gambar').src = init_img_src; } }
 <div class="intro"> <img id="gambar" src="https://via.placeholder.com/550" alt=""> </div>

You asked for Javascript code so:

Maybe you can run this in a window.onload . Depends on what you want.

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
  // returns true if its a mobile
  // change src here
  document.getElementById('gambar').src = "assets/images/image-intro-mobile.jpg";
}else{
  // returns false if it isn't
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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