我以为我对此非常聪明。我做了一个小功能,可以放大或缩小图像以适应浏览器窗口中的边距。一张图片效果很好。然后我想用几张图片来做,所以我可以点击同一窗口中的图像。我尝试使用.each,但收效甚微。它仅根据第一个图像的尺寸放大每个图像。显然,我希望每个图像都可以根据它自己的尺寸进行放大。
js bit:
$(window).bind("load resize", function(){
var ww = $(window).width();
var wh = $(window).height();
wh = wh-50;
ww = ww-225;
var wr = (ww/wh);
$("#slides div.scale img").each(function(){
var ow = $("img").width();
var oh = $("img").height();
var or = (ow/oh);
if (wr<or) {
$("img").css('width',ww);
$("img").css('height','auto');
}
else {
$("img").css('height',wh);
$("img").css('width','auto');
};
});
});
html位:
<div id="slides">
<div class="slide 1 scale"><img src="portrait.jpg" /></div>
<div class="slide 2 scale"><img src="landscape.jpg" /></div>
<div class="slide 3 scale"><img src="square.jpg" /></div>
<div class="slide 4 scale"><img src="portrait.jpg" /></div>
</div>
答案 0 :(得分:4)
$("#slides div.scale img").each(function(){
var ow = $(this).width();
var oh = $(this).height();
var or = (ow/oh);
if (wr<or) {
$(this).css('width',ww);
$(this).css('height','auto');
}
else {
$(this).css('height',wh);
$(this).css('width','auto');
};
});
试试吗?
我认为这需要改变
function changeimage(){
$("#slides div").css("visibility","hidden");
$('#slidetitles span').hide();
$("#slides div."+ns).css("visibility","visible");
$("#slidetitles span."+ns).show();
cs = ns;
};
答案 1 :(得分:2)
在每个内部,您需要使用$( this )
而不是$("img")
我已经为你做了这个改变,以及一些效率调整(但都未经测试)
$( function()
{
$( window ).bind( 'load resize', function()
{
var $win = $( this ),
ww = $win.width() - 50,
wh = $win.height() - 225,
wr = ( ww / wh );
$( '#slides div.scale img' ).each( function()
{
var $img = $( this ),
ow = $img.width(),
oh = $img.height(),
or = ( ow / oh ),
dimStyles;
if( wr < or )
{
dimStyles = {
width: ww,
height: 'auto'
};
}
else {
dimStyles = {
width: 'auto',
height: wh
};
}
$img.css( dimStyles );
} );
} );
} );
答案 2 :(得分:1)
每个循环中的选择器不会轮流获取每个图像,而是页面上所有img标记的数组。
在你的每个循环中,每次你引用一个图像时,使用$(this)代替表示你指的是当前循环主体的一个特定图像。
例如:
$(this).css('height');
答案 3 :(得分:1)
通过使用$(“img”)选择器,您仍然会选择页面上的所有img标记。 您应该使用$(this)来引用正在处理的当前项目