javascript - 动态加载图像后应用图像居中和裁剪

标签 javascript jquery html css image

即使对于稍后动态加载的图像,我也想居中和裁剪图像。

HTML

<body>
    <div class="iThumbnail">
        <img src="images/art-vertical.jpeg" alt=""/>
    </div>
</body>

上面的body内容第一次是静态的。 稍后,body 内容会动态加载/替换为其他图像源。

因此,对于静态内容,我可以使用以下代码将图像居中并裁剪(感谢 jonathanNicolnickCraver)。

$(document).ready(function() {
    function thumbnailImageCropCenter() {
        $('.iThumbnail').find('img').one('load', function() {
            if (($(this).height() > $(this).width()) && ($(this).height() != 0) ) {
                $(this).addClass('portraitView');
            }
        }).each(function() {
            if(this.complete) $(this).load();
        });
    }
    thumbnailImageCropCenter();
});

我想避免每次动态加载页面内容时调用 thumbnailImageCropCenter()

问题:有没有一种方法可以自动将thumbnailImageCropCenter()绑定(bind)到body,使其适用于body中的所有图像,没有如果稍后动态加载图像很重要。

PS:用 .bind() 替换 .one() 没有帮助。

最佳答案

$('body').on('load', '.iThumbnail img', function() {
  var $this = $(this);
  if (($this.height() > $this.width()) && ($this.height() != 0) ) {
       $this.addClass('portraitView');
  }
});

关于javascript - 动态加载图像后应用图像居中和裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060622/

相关文章:

javascript - babel-preset-es2016 需要 babel-runtime 的对等体,但没有安装

javascript - 如果完全在 View 中(大于视口(viewport)),intersectionObserver 获得比率 1

javascript - 使用 jquery 验证器插件设置十进制数的正则表达式

javascript - 从 url PhoneGap 加载动态外部图像

javascript - HTML 表单未在 Safari 和 iOS Safari 上提交

jquery - 无法使我的整个盒子大小的 <li> 元素成为超链接

javascript - 如何使用 JQuery 将动画内容移回悬停后的正常位置

javascript - 悬停多个实例 div 时发出独特的声音

html - 如何在实时网站上强制刷新背景图像?

html - 使用 CSS 将文本覆盖在图像之上