Owl carousel show a different image on mobile

2019-09-10 08:49发布

I've been using PageSpeed Insights from google to see how I can improve my website and the main point I'm getting is that my images are to large for mobile users. Currently I'm using the owl-carousel which came with the template I'm using.

Google automatically supplied me with resized images but I've got no idea how to implement these into the carousel. I tried something like https://github.com/teleject/hisrc but after trying it in multiple ways it just kept removing the images completely.

Anyone knows how I can automatically change the source depending on the screensize?

For instance on the desktop I'm showing mainimage.jpg and I would like to show mainimage-mobile.jpg if the screen gets smaller instead of just resizing it.

Here is my carousel:

(The style="position: relative" is required in order for the menu to stay on top of the image for chrome users)

<div class="line animated fadeIn "style="position: relative">
    <div class=" s-12 l-9 center cushycms" style="position: relative">
        <div id="owl-demo" class="owl-carousel owl-theme  margin-bottom">
        <div class="item" style="position: relative"><img style="position: relative" src="img/image1.jpg" alt="image"></div>
        <div class="item" style="position: relative"><img style="position: relative" src="img/image2.jpg" alt="image"></div>
        <div class="item" style="position: relative"><img style="position: relative" src="img/image3.jpg" alt="image"></div>
        <div class="item" style="position: relative"><img style="position: relative" src="img/image4.jpg" alt="image"></div>
        <div class="item" style="position: relative"><img style="position: relative" src="img/image5.jpg" alt="image"></div>
        </div>
    </div>
 </div>

Not sure if this is of any help but this is the template I'm using http://www.myresponsee.com/

2条回答
冷血范
2楼-- · 2019-09-10 09:16

You may be looking for width: width_you_want%; This makes it dependent on the screen size, the width being relative to that.

Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/width

查看更多
beautiful°
3楼-- · 2019-09-10 09:27

You could use <picture> element instead of just <img>.

For example:

<picture>
    <source srcset="mainimage-mobile.jpg" media="(max-width: 640px)">
    <img srcset="mainimage.jpg">
</picture>

In the above code the default mainimage.jpg is used, but once the screen is narrower that 641px - mainimage-mobile.jpg is used by the browser automatically.

The only problem with this approach might be browser support http://caniuse.com/#search=picture. But on the other hand, you could also include a javascript polyfill. https://github.com/scottjehl/picturefill

查看更多
登录 后发表回答