私はdivのX量を持っており、すべて特定の高さと幅に設定されています。これらの中にはイメージがあり、すべてサイズが異なります。私は画像の高さを見つけ出し、2で割ってそれを余白のトップ値として設定して、それが理にかなっていればすべての画像が中央にくるようにしたいのですか?アイブ氏はマージントップ=要素jQueryの50%
2
A
答えて
6
あなたはここにこの
$(document).ready(function() {
$('.box img').each(function() {
var $this = $(this);
var parentHeight = $this.parent().height();
var thisHeight = $this.height();
var topmargin = (parentHeight - thisHeight)/2;
$this.css("margin-top", topmargin);
});
})
2
$(document).ready(function(){
var boxheight = $('.box').height();
$('.box img').each(function(i){
var topmargin = (boxheight - $(this).height())/2
$(this).css("margin-top", topmargin);
});
})
ライブのような何かができる...フィドルだけそれについて移動する方法がわからないイム作ってみましたデモ
1
は、ここで私はいくつかの画像をロードするために時間がかかるので、まだの幅や高さを持っていないこと
$(document).ready(function(){
$('.box img').each(function() {
$(this).css("margin-top", $(this).parent().height()/2-$(this).height()/2);
});
});
0
を行うだろう方法です。この問題を解決するには、setTimeoutを使用します。
$(document).ready(function(){
$.each($('.box'), function(){
centerImage($(this));
});
});
function centerImage(box){
var imgWidth = $(box).find('img').width();
var imgHeight = $(box).find('img').height();
if(imgWidth > 0 && imgHeight > 0){
$(box).find('img').css('margin-top', ($(box).height() - imgHeight)/2);
} else {
setTimeout(function(){ centerImage(box); }, 100);
}
}
1
あなたは純粋なCSSのソリューションに興味があるなら:http://jsfiddle.net/R8QUL/11/
ちょうど `.innerHeightは()`あまりにもうまくいくかもしれないことを注目に値するかもしれ
.box
line-height: 225px;
}
.box img {
display: inline-block;
vertical-align: middle;
}
+0
今すぐ書く私はまたこの解決策を働いています:) – sandeep
関連する問題
- 1. フリーロールされていない要素で動作しないマージントップ
- 2. jQueryの - 要素
- 3. jQueryの要素
- 4. マージントップの問題
- 5. jquery要素コレクションのswitch要素位置
- 6. jquery mobile - フォーム要素の内部要素
- 7. jQueryのデータ要素
- 8. jquery要素のトップ
- 9. 空のjquery要素
- 10. jQueryのは、要素
- 11. のjQuery&param要素
- 12. は、jQueryの要素
- 13. jqueryのドラッグ要素
- 14. jQueryの:子要素
- 15. 要素のjquery order
- 16. のjQuery:要素ID
- 17. jQueryの「ハイライト」要素
- 18. jquery要素クロスフェードプラグイン
- 19. jquery append要素
- 20. jqueryカラーピッカーホバー要素
- 21. WPF相当のマージントップ?
- 22. jQuery UI要素とDojo(Dijit)フォーム要素
- 23. 「マージントップ:オートは」
- 24. は、CSSマージントップIE7
- 25. 編集LISTVIEW、マージントップ
- 26. jQuery update要素id
- 27. jquery event.target is_a_child_of(要素)
- 28. はJQuery&AJAX:form要素
- 29. jQueryの子要素の数
- 30. jqueryのは()次の要素
を追加これには「パディング」が含まれており、それは視覚的にボックス要素の内部の一部です。 Liamがしようとしていると判断して、おそらくこれも考慮しなければならないものかもしれないと私は想像しています。 –