javascript - 将网站中的所有图像降低一半高度

标签 javascript html css image

我们有一个包含许多数学公式的网站(显示为 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/

相关文章:

javascript - typeahead.bundle.js 如何通过在下拉建议上按 ENTER 开始搜索?

html - 使用 display flex 时不显示按钮文本(仅在 IE 中)

jquery - 如何在页面底部实现这种 "peeling"的效果呢?

jquery - 过渡或其他

javascript - 在 HTML + CSS 中将对象定位在图像上

javascript - 尝试将数组从内容脚本发送到弹出脚本的 Chrome 扩展程序错误

javascript - 发布到 npm, `main` 中定义的文件未发布

javascript - 从 JavaScript 到 servlet 的数组

javascript - 完全刷新页面 - Ctrl+F5

jquery - 静态链接 block ,如何设置事件类