javascript - 使用 Jquery 替换基于屏幕大小的图像

标签 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>

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

提前感谢您的帮助。

最佳答案

你需要使用jquery的resize函数。

工作 fiddle :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");
                });                        
    }         
});

希望这对您有所帮助!

关于javascript - 使用 Jquery 替换基于屏幕大小的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631607/

相关文章:

javascript - 将钩子(Hook)置于某种状态

javascript - $scope 值在 $interval 内不可预测

javascript - 将函数存储到数组会导致范围问题

javascript - JS - 在原型(prototype)函数中覆盖它

html - div在浏览器中导致x滚动的解决方案

javascript - 使用 Backbone 事件来切换 Collection View 属性或 jQuery.siblings()?

javascript - 尝试替换所有 anchor 中的内容,但内容未被替换

javascript - 如何检查javascript中以空格结尾的字符串?

php - AJAX:使用淡入追加数据

html - Bootstrap容器间距