Javascript 如何将溢出图像居中放置在约束div内

Javascript 如何将溢出图像居中放置在约束div内,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个240x240px的div,其中包含大小不同的图像的淡入淡出幻灯片。我将每个图像设置为高度:240px,宽度根据其高度自动调整。有些图像在比例上比宽的图像高,所以我使用position:relative将它们放在div的中心;margin:0 auto除了溢出240px分区的图像外,该功能运行良好。如何在溢出的分区内对图像进行居中处理?我尝试了这个jQuery,但由于某些原因,它不起作用。我确定我不明白: if( $("div img").width() > 240 ) {

我有一个240x240px的div,其中包含大小不同的图像的淡入淡出幻灯片。我将每个图像设置为高度:240px,宽度根据其高度自动调整。有些图像在比例上比宽的图像高,所以我使用position:relative将它们放在div的中心;margin:0 auto除了溢出240px分区的图像外,该功能运行良好。如何在溢出的分区内对图像进行居中处理?我尝试了这个jQuery,但由于某些原因,它不起作用。我确定我不明白:

if( $("div img").width() > 240 ) {
    $(this).css("margin-left", rv);
    var rv = -1 * ($(this).width() / 4) + "px";
}
逻辑是,如果图像在宽度上扩展div,则将其向左移动rvpx,rv为图像宽度的1/4,因为1/2会将图像在左侧截取一半,因此1/2的1/2有效地将其居中?我的第一个猜测是,我不能引用$this,因为我正在尝试,尽管我不知道

我知道我可以去添加单独的内联CSS样式,但那是杂乱无章的。我希望有一个脚本可以自动计算图像的中心,然后相应地移动它。有什么想法吗?

您只能使用CSS:


在图像上迭代,加载后获得图像宽度和父元素宽度,比较宽度,如果图像比父元素宽,则获得差值的一半,并从左边距中减去差值,使图像水平居中

$("div.centered img").each(function(_,el) {
    var img    = new Image(),
        parent = $(el).parent();

    img.onload = function() {
        var ma = this.width - $(parent).width();
        if ( ma > 0 ) {
            $(el).css('margin-left', ((ma/2) * -1));
        }
    }
    img.src = this.src;
    if (img.complete) img.onload();
});

我推荐如下:

div.center-img { background:url('/path/img.jpg') center center no-repeat; }
$('div img').each(function() {
    if( this.width > 240 )
        $(this).css("margin-left", ((this.width - 240) / -2) + "px");
});
但你的问题可以这样回答:

div.center-img { background:url('/path/img.jpg') center center no-repeat; }
$('div img').each(function() {
    if( this.width > 240 )
        $(this).css("margin-left", ((this.width - 240) / -2) + "px");
});

谢谢,第二点帮助了我。