2013-12-11 39 views
0

我有一個很奇怪的問題(或者我只是努力了很多,以找到提示)。我想用帶有可擴展字幕的圖像居中。這裏是我的代碼:jQuery:獲取渲染圖像的寬度,以它爲中心

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') 
    // ... 
}); 

感謝您的幫助!

+0

'$ el.parent()。width($ el.width());'??? –

+0

仍然同樣的輸出:( –

回答

1

請查看本的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; 
} 

希望它能幫助。

+0

是的,這有幫助!感謝提示,偉大的工作! –

0

試試這個:

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

不,仍然是相同的輸出。我總是隻得到自然大小,不是顯示的一個...使用jQuery 1.10.1 btw。 –