在调整浏览器大小时使用jQuery更改图像src

我有两个不同大小的图像,一个用于小于759像素的屏幕,另一个用于大于759像素的屏幕。

我已设法在文档加载时根据窗口宽度更改图像的来源。 但我真的希望能够在浏览器resize时也能做到这一点但是对于我的生活我无法做到这一点,它似乎只在页面初始加载时起作用。

这是我的代码:

$(document).ready(function() { function imageresize() { var contentwidth = $(window).width(); if ((contentwidth) < '700'){ $('.fluidimage').each(function(){ var thisImg = $(this); var newSrc = thisImg.attr('src').replace('x2', 'x1'); thisImg.attr('src', newSrc); }); } else { $('.fluidimage').each(function(){ var thisImg = $(this); var newSrc = thisImg.attr('src').replace('x1', 'x2'); thisImg.attr('src', newSrc); }); } } imageresize();//Triggers when document first loads $(window).bind("resize", function(){//Adjusts image when browser resized imageresize(); }); }); 

先试试这个……

改变你的以下代码行

 $(window).bind("resize", function(){//Adjusts image when browser resized imageresize(); }); 

 // Bind event listener $(window).resize(imageresize); 

并在imageresize内放置警报以查看它是否有效……

如果上面没有成功…我相信可能有一个问题..

在你的代码中

 $(document).ready(function() { $(window).bind("resize", function(){//Adjusts image when browser resized imageresize(); }); } 

因此驻留在jquery中的函数可能效果不佳。 最重要的是尝试使用简单的JavaScript; 我有类似的问题,解决使用普通的JavaScript和jquery在某些浏览器中不起作用。

声音很奇怪,阻止你尝试它,但会工作……

尝试使用css3媒体查询,而不是在jQuery或javascript中执行。

http://sofzh.miximages.com/jquery/ w 600px到900px; x2.jpg将被加载。 默认情况下,将使用x1.jpg。

例如:

 .img-src { background-image: url("http://sofzh.miximages.com/jquery/x1.jpg"); } @media (min-device-width:600px) and (max-width:900px) { .img-src { background-image: url("http://sofzh.miximages.com/jquery/x2.jpg"); } } 

这不是jQuery,但你可以简单地使用document.getElementById("myId").src="another.jpg"; 定义id为“myId”的img的新src。

正如我所看到的,您的代码工作正常,但我更喜欢使用setTimeout ,有时页面可能会减慢而不resize暂停。

 $(document).ready(function() { var resizeTimer, $window = $(window); function imageresize() { if ($window.width() < 700) { $('.fluidimage').text('< 700'); } else { $('.fluidimage').text('>= 700'); } } imageresize();//Triggers when document first loads $window.resize(function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(imageresize, 100); }); }); 

示例: jsfiddle.net/SAbsG/