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

标签 javascript jquery document-ready

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

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

功能如下:

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/

相关文章:

javascript - 简单 Javascript 代码中的奇怪问题,非空数组参数达到函数空

jquery - 悬停图像在 FF Chrome 中抖动,但在 IE10 中则不然

javascript - 当 jQuery 选择器从控制台运行时,什么会导致它在 document.ready 之后失败?

javascript - UI 未检测到可观察数组

Javascript 输入 <a href="http ://www. website.com/OUTPUT HERE

javascript - 如何检索任何 Wordpress 页面上所有 WooCommerce 数据的 JSON?

javascript - 有没有更好的方法来覆盖 JS ajax 回调?

jquery - 将 CSS 添加到使用 jQuery 创建的表格行

javascript - jQuery 文档就绪无论我怎么写都无法工作

jquery - $(document).ready 有必要吗?