脚本的功能在调整大小时正常工作,但在document.ready上没有

时间:2013-07-18 10:23:47

标签: 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

那么错误在哪里呢?

即使在开始时也会调用脚本,如果我在函数中添加警报,并且只是加载页面(没有调整大小),则会弹出警报。

3 个答案:

答案 0 :(得分:1)

据我所知,您应该设置图像的属性宽度和高度,并使用文档就绪处理程序:

.links-image DIV中所有图片的HTML:{width / height / alt属性应尽可能为图片指定}

<div class="links-image" style="margin-top: 53px;">
    <img src="img/list.png" width="210" height="92" alt="">
</div>

JS代码:

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

答案 1 :(得分:1)

当您计算 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

答案 2 :(得分:1)

我的前提是你希望盒子内容组件 - 标题,副标题和图像 - 在所有三个盒子中垂直对齐。如果不是这样,请忽略这个答案。

虽然我无法在手头的代码中发现问题,但我会尝试以另一种方式处理它,没有JS:清除列并修复组件的高度:让我们说我希望标题是一行文字,字幕三行和图像已经固定高度。

固定高度将为您提供垂直对齐,并且clearfix将处理列高。