javascript - 如何调整通过 ajax 添加的图像的大小以适应特定尺寸,同时使用 JQuery/CSS 保持纵横比?

标签 javascript jquery html css ajax

我有一个 Web 应用程序,它通过 ajax 调用从外部源加载一些内容到 dom,返回的内容之一是一组图像(不同大小和纵横比)显示在个人资料照片部分。我希望调整每个图像的大小以适应 64px x 64px 区域内,并且我想保持宽高比。我能够在 firefox、chrome 和 safari 中做到这一点,但我没有运气让它在 IE 7 或 8 中工作。我遇到的问题是找到一个 jquery 事件,该事件在图像加载后可靠地触发,因为图片是在页面加载后添加的。以下是在列出的浏览器中的工作原理:

$(window).load(function () {
        $('.profileThumbnail').each(function (i) {
            var divHeight = $(this).height();
            var divWidth = $(this).width();
            if (divHeight > divWidth) {
                $(this).css('height', '64px');
                $(this).css('width', 'auto');
            }
            else {
                $(this).css('height', 'auto');
                $(this).css('width', '64px');
            }

            divHeight = $(this).height();
            var divParentHeight = $(this).parent().parent().height();
            var divNewHeight = (divParentHeight - divHeight) / 2;
            $(this).parent().css('top', divNewHeight);
            divWidth = $(this).width();
            var divParentWidth = $(this).parent().parent().width();
            var divNewWidth = (divParentWidth - divWidth) / 2;
            $(this).parent().css('left', divNewWidth);
        });
    });

我也试图将它们居中(水平和垂直),这是该代码的其余部分所做的,但我认为如果我能找到一种方法在图像之后触发此代码,我已经完成了所有这些工作在 IE 中加载。

请记住,这需要在第一次访问(未缓存)和后续访问(缓存)时都起作用。我正在寻找 jquery、javascript 或 css 解决方案,因为我想避免每个图像的往返/带宽。

最佳答案

您是否厌倦了自己为图像添加一个加载事件,该事件在图像加载时触发?这就是图像预加载器的工作方式。

var img = document.createElement("img");
img.onload = function(){ alert('loaded'); }
img.onerror = function(){ alert('error'); }
img.src = "foo.png";

如果您不使用预加载方法,则可以将 onload 添加到图像元素本身。

关于javascript - 如何调整通过 ajax 添加的图像的大小以适应特定尺寸,同时使用 JQuery/CSS 保持纵横比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3799599/

相关文章:

javascript - 如何仅在大括号之外搜索正则表达式

javascript - 有什么优雅的方式告诉 IE7 及以下版本的用户离开吗?

javascript - 从 jquery 更新 html 文本数据

html - 强制单选按钮显示内联

javascript - 安装后找不到 gulp run 命令

javascript - 从对象内部的函数调用函数(对象字面量)

javascript - 时间戳 php 转 jquery 格式

javascript - 获取 Json 文件时出错

java - 页面滚动时滚动模态框

javascript - 将光标移动到输入字段的开头?