我们有一个包含许多数学公式的网站(显示为 png,从 Latex 转换而来)并且它们被动态加载到各自的位置(从 sql 数据库中)。
所有公式都与正文一致。你知道这一行:_______________
。
我们希望有一个函数来获取特定类的每个元素(或通过在 css 中使用“img”),我们可以使用它自动将所有 img 向下移动相应图像高度的一半。
有没有我忽略的简单解决方案,或者我们真的必须手动定位每张图片(遗憾的是,会有数百张!)?
最佳答案
纯 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));
});
关于javascript - 将网站中的所有图像降低一半高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7879283/