javascript - jQuery图像调整大小出现在整个屏幕上

标签 javascript jquery css

我添加了 jQuery 函数来调整个人资料图片的大小以适应一个 div(200px 200px 并且不确定该函数是否正确),但是每次我刷新页面时该函数都会再次执行并且图片显示在整个屏幕只是一秒钟!我怎样才能防止这种情况?我的功能:

$(document).ready(function () {
    $('.profile-picture img').each(function() {

        var width = $(this).width();
        var height = $(this).height();

        if(width > height) {
            $(this).css("max-width", "100%");
            $(this).css("height", "100%");
        }else {
            $(this).css("width", "100%");
            $(this).css("max-height", "100%");
        }
    });
});

在一篇帖子中,我发现答案是:“你必须通过回调来完成”,但不知道如何做。你能给我建议吗?提前致谢!

最佳答案

.ready() 事件在浏览器呈现页面后触发。为防止出现您描述的问题,您应该在 CSS 中设置一些默认值。

更进一步,您可以在 CSS 中设置所有样式,然后只使用 Javascript 中的类。

CSS:

.profile-picture {
  width: 200px;
  height: 200px;
}
.profile-picture img {
  width: 100%;
  max-height: 100%;
}
.profile-picture img.tall {
  max-width: 100%;
  height: 100%;
}

Javascript:

$(document).ready(function () {
  $('.profile-picture img').each(function() {
    if($(this).width() < $(this).height()) {
      $(this).addClass('tall');
    }
  });
});

关于javascript - jQuery图像调整大小出现在整个屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42860638/

相关文章:

javascript - 等待所有功能和请求完成

Javascript:找到每年出现周的开始

javascript - 使用CSS过渡时如何更改父div的高度?

css - 为您的整个网站使用 jQuery 主题是错误的吗?

javascript - 我可以让我的 Ajax 调用导致出现 "in-progress"光标吗?

javascript - 在谷歌地图 API v3 的循环中添加标记监听器?

javascript - JS 正则表达式 : replace all digits in string

javascript - 下载前倒计时仅适用于第一个按钮

javascript - Jquery动态预加载图像

html - 在 div 中加载新 html 时避免 CSS 覆盖