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

Javascript jQuery:获取渲染图像宽度以使其居中,javascript,jquery,image,width,image-size,Javascript,Jquery,Image,Width,Image Size,我有一个非常奇怪的问题(或者可能我只是花了很多时间才找到这个提示)。我想中心的字幕是可伸缩的图像。这是我的密码: HTML 现在是有趣的部分。我想获取图像的当前宽度并将其应用于.child文本对齐:居中不起作用,这会导致我的标题也位于居中 但是–如果我读取图像的宽度,我总是得到它的自然大小,而不是它的大小。我真的很困惑,我想这很明显。。。这是我迄今为止尝试过的JS Javascript $(window).load(function(){ var $el = $('.child').fi

我有一个非常奇怪的问题(或者可能我只是花了很多时间才找到这个提示)。我想中心的字幕是可伸缩的图像。这是我的密码:

HTML

现在是有趣的部分。我想获取图像的当前宽度并将其应用于.child<代码>文本对齐:居中不起作用,这会导致我的标题也位于居中

但是–如果我读取图像的宽度,我总是得到它的自然大小,而不是它的大小。我真的很困惑,我想这很明显。。。这是我迄今为止尝试过的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')
    // ...
});
谢谢你的帮助

试试这个:

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

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

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

文本在中心对齐,并且当图像宽度和高度更改时,子对象也会更改

HTML:


希望有帮助。

$el.parent().width($el.width())???不,仍然是相同的输出。我总是只得到自然尺寸,而不是显示的尺寸。。。使用jQuery 1.10.1 btw。
$(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')
    // ...
});
$(window).load(function(){
$('.child').find('img').css({'width':parseInt($('.child').find('img').width())+'px', 'margin':'0 auto'});
});
<div class="parent">
    <div class="child">
        <img class="image" id="image" src="image.jpg" alt=""/>
            <br/>
        <div class="title">Title</div>
    </div>
</div>
.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;
}