问题描述
我有两个不同尺寸的图像,一个是用于小于759px的屏幕,另一个是用于大于759px的屏幕.
I have two different sized images, one if for screens smaller than 759px, the other is for screens larger than 759px.
我设法获取了图像的来源,以便在文档加载时根据窗口宽度进行更改.但是我真的很希望能够在调整浏览器大小的同时执行此操作,但是对于我一生来说,我无法做到这一点,它似乎仅在最初加载页面时有效.
I have managed to get the source of the images to change when the document loads depending on the window width. But I really would like to be able to do this when the browser is resized as well but for the life of me I can't get it to do that, it only seems to work when the page is initially loaded.
这是我的代码:
$(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中以查看其是否有效...
and put alert inside imageresize to see if it works or not...
如果上述方法无法解决...我认为可能存在一个问题.
In case above do not work out...I believe there is one problem probably..
您的代码中有
$(document).ready(function() {
$(window).bind("resize", function(){//Adjusts image when browser resized
imageresize();
});
}
因此,驻留在jquery中的函数可能无法正常工作.最重要的是,尝试使用简单的javascript;我有类似的问题,并使用普通的javascript解决了,jQuery在某些浏览器中无法正常工作.
So the function for reside inside jquery which may not work well. On top of that try using simple javascript; i had similar problem and solved using plain javascript and jquery did not work in some browsers.
声音听起来很奇怪,足以阻止您尝试,但可以正常工作...
Sound strange enough to stop you try at it but would work...
这篇关于调整浏览器大小时使用jQuery更改图像src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!