gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:08:05 24 4
gpt4 key购买 nike

我添加了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com