使用Javascript / JQuery进行媒体查询 - 根据屏幕大小更改图像

时间:2018-05-07 20:39:06

标签: javascript jquery html css

我已经开发了一个解决方案来根据屏幕大小更改src的值,但不知何故,即使我调整浏览器大小,它也只显示第一个图像(../assets/img/features/cleardent-header。 PNG)。我希望它在屏幕尺寸小于991时更改为(../assets/img/features/cleardent-header-small.png。

我正在考虑使用CSS,但由于它在旋转木马中,因此有点复杂。有人能给我一个建议吗?

这是我的旋转木马的第一张幻灯片的HTML:

<div class="item active"> <img id="first-slide" class="first-slide" alt="First slide"> 
    <!--slogan and CTA-->
    <div class="container carousel-caption main-slider">
        <div class="row header-slogan fadeInDown animated">
            <div class="col-xs-12">
                <section class="cd-intro">
                    <h1 class="cd-headline letters type"><span>Do everything.</span> <span class="cd-words-wrapper ahwaiting"><b class="is-visible">Better.</b><b class="colour-cleardent">with ClearDent</b></span></h1>
                </section>
            </div>
        </div>
        <div class="row header-tagline fadeInDown animated">
            <div class="col-xs-12">
                <p>A complete dental practice management program that you are going to <span class="colour-cleardent-sec">love</span></p>
            </div>
        </div>
        <div class="row header-cta fadeInUp animated">
            <div class="col-xs-12">
                <button class="btn-u extra-demo-btns" onClick="window.location='../demo';"><i class="fa fa-paper-plane fa-fw"></i> Book a Demo</button>
                &nbsp; <a href="https://player.vimeo.com/video/157093017" class="btn-u fancybox-media fbmloading" id="cleardent-page-header-2-vimeo" data-fancybox-title="Why ClearDent?"><i class="fa fa-play fa-fw"></i> Watch a Video</a> 
            </div>
        </div>
    </div>
    <!--slogan and CTA end--> 
</div>

这是我的jQuery:

      <script>
  $(document).ready(function() {
     if($(window).width() > 991) {
         $("#first-slide").attr("src", "../assets/img/features/cleardent-header.png");
     } else {
         $("#first-slide").attr("src", "../assets/img/features/cleardent-header-small.png");
     }
}); 
  </script>

2 个答案:

答案 0 :(得分:1)

您的代码适用于DOM的初始加载,但是一旦文档加载并且用户调整浏览器窗口大小就没有影响,您需要将处理程序连接到window.resize事件以在窗口大小时发出警报改变,然后做同样的逻辑:

//Place this in your document ready
$(window).resize(function() {
     if($(window).width() > 991) {
         $("#first-slide").attr("src", "../assets/img/features/cleardent-header.png");
     } else {
         $("#first-slide").attr("src", "../assets/img/features/cleardent-header-small.png");
     }
});

答案 1 :(得分:0)

srcset怎么样?

<img src="../assets/img/features/cleardent-header-small.png" srcset="../assets/img/features/cleardent-header.png 991w, evenLargerImage.jpg 2000w">