将网站中的所有图像向下移动一半高度

时间:2011-10-24 17:15:49

标签: javascript html css image dynamic-websites

我们有一个包含许多数学公式的网站(显示为png,从Latex转换而来),它们被动态加载到各自的位置(在sql-database之外)。

所有公式都与文本一致。你知道这一行:_______________

我们希望有一个函数来获取某个类的每个元素(或者在css中使用“img”),我们可以自动将所有imgs向下移动到相应图像高度的一半。

是否有一个我忽视的简单解决方案,或者我们是否必须手动定位每个图像(遗憾的是,会有数百个!)?

2 个答案:

答案 0 :(得分:1)

纯Javascript解决方案:

//All of your images with class : class
var images = document.getElementsByClassName("class");

//Iterates through each of the images
for (var i = images.length - 1; i >= 0; i--)
{
    //Sets the images top margin to the half of the height of the image
    images[i].style.marginTop = images[i].style.height / 2;
}

jQuery解决方案:

如果jQuery是一个选项,您可以使用.each()函数在相应设置高度的情况下对每个函数进行交互:

$('.class').each(function()
{
    //Get Item Height
    var height = $(this).height();

    //Move Item Down By Half of Height
    $(this).css('margin-top',height/2);
});

更简洁:

$('.class').each(function(){
    $(this).css('margin-top',($(this).height()/2));
});

答案 1 :(得分:0)

Rionmonster说的是什么,除了我要添加它以获得图像的高度(或任何尺寸),我一直不得不说:

theHeight = parseFloat( element.style.height );

parseFLoat()因为它将处理parseInt()可以处理的任何内容,而反之则不然。