jQuery:获取渲染图像的宽度以使其居中

jQuery: get rendered image width to center it

本文关键字:获取 图像 jQuery      更新时间:2023-09-26

我有一个非常奇怪的问题(或者我只是花了很多时间来寻找提示)。我想把一个可缩放的带字幕的图像居中。这是我的代码:

HTML

<div class="parent">
    <div class="child">
        <img src="image.jpg" alt="">
        <br>
        <div>Title</div>
    </div>
</div>

CSS

.parent {
    width: 66%;
}
.child {
    width: auto;
    height: auto;
    margin: auto;
}
.child img {
    max-width: 100%;
    max-height: 95%;
    height: auto;
    width: auto;
}
.child div {
    display: inline;
    font-style: italic;
}

现在是有趣的部分。我想获得图像的当前宽度,并将其应用于.child;text-align: center不起作用,这会导致我的头衔也在中心。

但是,如果我读出图像的宽度,我总是得到它的自然大小,而不是调整大小的大小。我真的很困惑,我想这很明显。。。这是我迄今为止尝试过的JS。

Javascript

$(window).load(function(){
    var $el = $('.child').find('img');
    $el.parent().css('width', $(this).width());
    // I also tried $(this).get(0).width, $(el).width() and $(el).css('width')
    // ...
});

谢谢你的帮助!

请检查我创建的这个jsfiddle,它可能是你需要的:

http://jsfiddle.net/2kC3q/2/

我将图像设置为可调整大小(以模拟可缩放)。

文本居中对齐,当图像的宽度和高度发生变化时,子图像也会对齐。

HTML:

<div class="parent">
    <div class="child">
        <img class="image" id="image" src="image.jpg" alt=""/>
            <br/>
        <div class="title">Title</div>
    </div>
</div>

CSS:

.parent {
    width: 66%;
}
.child {
    width: auto;
    height: auto;
    margin: auto;
    border: 1px solid black;
    display: inline-block;
}
.image{
    max-width: 100%;
    max-height: 100%;
    min-width: 50px;
    min-height: 50px;
    display: block;
    border: 1px solid red;
}
.title{
    text-align: center;
    display: block;
    font-style: italic;
}

希望能有所帮助。

试试这个:

$(window).load(function(){
$('.child').find('img').css({'width':parseInt($('.child').find('img').width())+'px', 'margin':'0 auto'});
});