【发布时间】:2012-01-17 19:56:26
【问题描述】:
此代码应该在其方形 div 框内重新定位画廊图像。所有图像都有一个设定的高度,例如100像素。但它们的宽度不同。与其只显示每张图片最左边的 100px,我更希望它显示中心。
我只需要遍历每个 img 并更改 left 属性以将图像向左移动。
$('img.gall_imgs').load(function() {
var $imgWidth = parseInt($(this).width); // "$(this)" or "this"? parseInt() needed?
var $divWidth = parseInt($(this).closest('div').width);
if($imgWidth > $divWidth) { // if img is wider than its containing div, we'll shift it left
var $position = -1 * ($imgWidth/2 - $divWidth/2); // will give decimals?
$position = parseInt($position) + "px"; // make $position format "123px". parseInt() needed here?
// var $position = '-50px'; // tested with pre-set position
this.css("left", $position); // "$(this)" or "this"?
}
//}
});
另外,我什至不知道如何在 jquery 中测试变量值。我尝试输入警报($imgWidth),但显然没有用。
编辑:这是我现在拥有的 CSS 和 HTML:
.gall_thumb_img { // the div surrounding the img
width:200px;
height:200px;
margin-left:auto;
margin-right:auto;
overflow:hidden;
text-align:center; // just added this per suggestions. No effect
}
.gall_thumb_img img{ // the img
position:absolute;
display:block;
height:200px;
min-width:200px;
}
HTML:
<div id="gall_box">
<div class="gall_thumb_box" id="gall_thumb_box_0" >
<div class="gall_thumb_img" id="gall_thumb_img_0" >
<a href="?c=ecards&v=single&idx=23&img_dir=nature">
<img class="gall_img" id="img0" src="http://example.com/small.jpg?20111211044810"></a>
</div>
</div>
</div>
EDIT2:这是我根据各种建议将 jquery 更改为的内容。最终结果仍然没有变化。
$(window).load(function() {
$('img.gall_imgs').each(function() {
var imgWidth = $(this).width(); // "$(this)" or "this"?
var divWidth = $(this).closest('div').width();
alert(imgWidth);
if(imgWidth > divWidth) {
var position = -1 * (imgWidth/2 - divWidth/2); // will give decimals?
position = position + "px"; // make position format "123px".
// var position = '-50px'; // tested with set position
this.css("left", position); // "$(this)" or "this"?
}
});
});
文本对齐中心是一个好主意,如果我可以让它工作,我会使用它,但我仍然想知道为什么我的 jquery 代码不起作用。谢谢。
【问题讨论】:
标签: jquery image jquery-selectors