2010-05-07 50 views
1

好吧,我是一个完整的初学者,事实上我仍在建立我的第一个网站。我试图通过手工编码而不使用CMS来尝试尽可能快地学习。如果这篇文章是在错误的地方,我表示歉意,并指向正确的地方,将不胜感激。如何使用jQuery垂直对齐未知高度的缩略图?

在这里,我想拼凑一些jQuery,它会自动垂直对齐我的图片库中的缩略图(它们都是不同的大小)。他们是内固定大小的div和我试图函数看起来是这样的:

<script type="text/javascript"> 

$('#ul.photo).bind(function() { 

var smartVert=$(this); 

var phty=ob.("ul.photo img").height(); //get height of photos 

var phtdif=Math.floor(208 - phty); //subtract height of photo from div height 

var phttop=Math.floor(phtdif/2); //gets padding reqd. 

$ob.("ul.photo").css({'padding-top' : phttop}) //sets padding to center thumbnail 

}); 

smartVert(); 

</script> 

不出所料,这并不工作,如果一些好心的灵魂会怜惜共小白,并指出我要去的地方错误的(可能在写作完成时,我的第一个猜测是乱码),这将是非常感谢 - 即使你可以指向我的教程方向关于这些事情。我曾看过并发现一篇文章提到这种功能很容易创建,但没有详细说明。

回答

1

made some code here for you

例如:

HTML

<div id="yourdiv"> 
    <img height="200" width="100" src="x" /> 
    <img height="100" width="100" src="x" /> 
    <img height="150" width="100" src="x" /> 
    <img height="300" width="100" src="x" /> 
</div>​ 

CSS

#yourdiv { 
    height: 400px; 
    background-color: black; 
} 
#yourdiv img { 
    margin: 0 10px; 
} 

JS

$(document).ready(function() { 
    var $yourdiv = $("#yourdiv"); 
    var divHeight = $yourdiv.height(); 

    $("img",$yourdiv).each(function() { 
     var imgElement = $(this); 
     var imgPadding = (Math.floor((divHeight-imgElement.height())/2)); 
     imgElement.css('margin-top',imgPadding+'px'); 
    }); 
});​ 

编辑:

为更好地协调:设置你的图片封锁和浮动他们离开。然后清除你的div。

编辑2:

通过对象集与一个for循环比使用.each

+0

你没有确定你的任何变量... – gnarf 2010-05-07 20:35:56

+0

作用域和缓存 – choise 2010-05-07 21:16:32

+0

Thankyou,但我试图使用变量image-液体布局内的尺寸。这可能是事实证明是超出我的方式,但除了这个垂直对齐问题,它似乎很好地融合在一起............ 我真的很感激你花时间去顺便回答我,有点害怕我会因为不知道我在另一个论坛上做过的事情而被咀嚼掉 – user335780 2010-05-08 17:01:12

0

假设$('#ul.photo')包含多个<img>标签更快的循环:

$('#ul.photo img').each(function() { 
    var $img = $(this); 
    $img.css('padding-top', (208 - $img.height())); 
}); 
+0

谢谢,我感谢您花时间回答我的问题,但我认为我没有正确解释自己。抱歉。看看我上面的评论以获得更好的解释(我想!)。 – user335780 2010-05-08 17:07:22

0

这里是CSS的我的图库:

.contentphoto { 
    position:relative; 
     width:64% 
    margin:auto; 
    left:10.375em; 
    top:-36.625em; 
    background-color: #7EC0EE; 
    background-image: none; 
    background-repeat: no-repeat; 
    background-position:center; 
    z-index:1; 
} 

ul.gallery{ 
    width: 100%; 
    padding-left: 3.2em; 
    margin: 0; 
    list-style: none; 
} 

ul.gallery li { 
    float: left; 
    width: 200px;   /*Set default width*/ 
    padding: 0; 
    margin: 5px 0; 
    display: inline; 
} 

.photo { 
    height: 13em; 
    font-size: 1em; 
    margin-right: 10px; /*Creates the 10px gap */ 
    padding: 20px; 
    background: #e3e1d5; 
} 

.photo img {  /*Flexible image size with border*/ 
     width: 89%; /*Took 1% off of the width for IE6 bug*/ 
     padding: 5%; 
    background:#fff; 
    margin: 0 auto; 
    display: block; 
    -ms-interpolation-mode: bicubic; 

对不起,把它放在另一个答案框中,但评论按钮停止工作...