gpt4 book ai didi

javascript - 脚本的函数在调整大小时可以正常工作,但在 document.ready 上却不能正常工作

转载 作者:行者123 更新时间:2023-11-28 20:24:03 25 4
gpt4 key购买 nike

我有一个函数可以纠正和调整带有文本和图像的三个流体列的大小(和垂直对齐方式)。

该脚本虽然尚未完善/高效,但其工作原理与预期完全一致,但有时(?)一开始就会失败。

功能如下:

var resetHeight = function(){
var maxHeight = 0;
$(".same-height-col").height("auto").each(function(){
maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
}).height(maxHeight + 25);
var maxTextSize = 0;
var tempHeight;
$(".same-height-col").each(function(){
tempHeight = $(this).find(".links-text").height();
maxTextSize = tempHeight > maxTextSize ? tempHeight : maxTextSize;
});
var topMargin;
$(".same-height-col").each(function(){
topMargin = (maxTextSize - $(this).find(".links-text").height()) + 25;
$(this).find(".links-image").css("margin-top",topMargin);
});
}

我调用了两次:

$(document).ready(function() {
resetHeight();
$(window).resize(function() {
resetHeight();
});
});

问题是,很多时候当我加载页面时,我会看到以下内容:

enter image description here

这种情况不会持续发生,但确实经常发生,但是一旦我调整窗口大小,脚本就会完全按照预期工作:

enter image description here

那么错误可能出在哪里呢?

即使在开始时也肯定会调用脚本,如果我在函数中放置警报,然后仅加载页面(不调整大小),则会弹出警报。

最佳答案

当您计算 maxHeight 值时,您可以通过执行 $(".same-height-col").height("auto") 重置在先前的 ResetHeight 调用中设置的所有内联高度。 。但是,您不会重置添加到 links-image 元素的 margin-top 属性。

这意味着第二次调用resetHeight(以及所有后续时间),maxHeight 计算将有所不同。为了确保每次结果都相同,您需要在计算之前重置 links-image 元素上的 margin-top 属性。

$(".same-height-col .links-image").css("margin-top","");
$(".same-height-col").height("auto").each(function(){
maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
}).height(maxHeight + 25);

您可能还想将高度设为 maxHeight+50而不是maxHeight+25如果您认为调整大小后的布局结果看起来比加载时的初始布局更好。

关于javascript - 脚本的函数在调整大小时可以正常工作,但在 document.ready 上却不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17720843/

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