使用Jquery根据屏幕大小替换图像

时间:2016-09-22 06:18:57

标签: javascript jquery html css

我正在尝试根据屏幕大小更改图像src。

       $(document).ready(function() {
				$(function() {
  				if($(window).width() < 568) {
    				$("#crewimage").each(function() {
      				$(this).attr("src", $(this).attr("src").replace("resources/images/thecrew.png", "resources/images/thecrewmobile.png"));
    				});
  				} else if ($(window).width() >= 568) {
    				$("#crewimage").each(function() {
      				$(this).attr("src", $(this).attr("src").replace("resources/images/thecrewmobile.png", "resources/images/thecrew.png"));
    				});
					}
				});
			});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="crew-content">
	    <img id="crewimage" src="resources/images/thecrew.png" alt="Header Image"></img>
	</div>

我的逻辑似乎很扎实。我不确定为什么它不起作用。

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

您需要使用jquery的resize函数。

工作小提琴https://jsfiddle.net/f0ngoLkq/1/

<强> HTML

<div id="crew-content">
    <img id="crewimage" src="http://completewebgraphics.com/wp-content/uploads/2015/11/Mobile-Apps-Development-in-India.jpg" alt="Header Image" />
</div>

jQuery代码

$(window).resize(function(e){
   if($(window).width() < 568) {
   console.log($(window).width());
    $("#crewimage").each(function() {
      $(this).attr("src", "http://s3.amazonaws.com/libapps/customers/1633/images/icon_52143.png");
                });
            } else if ($(window).width() >= 568) {
                $("#crewimage").each(function() {
                $(this).attr("src","https://ithemes.com/wp-content/uploads/2012/07/mobile300.png");
                });                        
    }         
});

希望这有帮助!

答案 1 :(得分:0)

不要使用替换:

 <img class="crewimage" src="resources/images/thecrew.png" alt="Header Image"></img>

            $(function() {
            if($(window).width() < 568) {
                $(".crewimage").each(function() {
                $(this).attr("src","resources/images/thecrewmobile.png");
                });
            } else if ($(window).width() >= 568) {
                $(".crewimage").each(function() {
                $(this).attr("src","resources/images/thecrew.png");
                });
                }
            });

注意:只有在窗口调整大小后刷新页面才会更改图像,如果要在调整大小时自动更改,请使用resize event

如果你有多个div,如果只有一个div删除每个循环,

第二次将id更改为类

答案 2 :(得分:0)

使用窗口调整大小

$(window).resize(function(){

    $(function() {
            if($(window).width() < 568) {
                $(".crewimage").each(function() {
                $(this).attr("src","resources/images/thecrewmobile.png");
                });
                });
            } else if ($(window).width() >= 568) {
                $(".crewimage").each(function() {
            $(this).attr("src","resources/images/thecrew.png");
            });
            });
});