【问题标题】:Jquery calcutate width issue while first time loadJquery在第一次加载时计算宽度问题
【发布时间】:2013-04-22 05:15:35
【问题描述】:

页面第一次加载时出现累积添加的图像。Jquery 不会动态计算宽度,但在第二次加载或页面刷新后正常出现。可能是什么原因?

Javascript:

$(function(){
    var imageWidth, totalWidth, sliderContent, $slider;
    $slider = $("#slider");
    sliderContent = $slider.html();
    $slider.html("<div id=\"slideWrapper\">" + sliderContent + "</div>");
    imageWidth = $slider.find("img").width();
    totalWidth = $slider.find("img").size() * imageWidth;
    $("#slider").css("width", imageWidth);
    $("#slideWrapper").css("width", totalWidth);

    $(".next-arr").click(function () {
        if (parseInt($("#slideWrapper").css("margin-left")) < 0 && !$("#slideWrapper").is(":animated")) {
            $("#slideWrapper").stop(true, true).animate({ marginLeft: "+=" + imageWidth + "px" }, 1600);
        }
    });

    $(".prev-arr").click(function () {
        if ((parseInt($("#slideWrapper").css("margin-left")) * -1) < (totalWidth - imageWidth) && !$("#slideWrapper").is(":animated")) {
            $("#slideWrapper").stop(true, true).animate({ marginLeft: "-=" + imageWidth + "px" }, 1600);
        }
    });
});

HTML:

<div id="slider">
    <a href="#" title="img">
        <img src="img.jpg" alt="img" /></a>
    <a href="#" title="img">
        <img src="img.jpg" alt="img" /></a>
    <a href="#" title="img">
        <img src="img.jpg" alt="img" /></a>
    <a href="#" title="img">
        <img src="img.jpg" alt="img" /></a>
</div>

CSS:

#slider {
    overflow: hidden;
}

    #slider a, #slider img {
        float: left;
        overflow: auto;
        position: relative;
    }

    #slideWrapper {
        overflow: hidden;
    }

        #slideWrapper img {
            float: left;
        }

【问题讨论】:

    标签: jquery width banner


    【解决方案1】:

    您可以使用$(window).load 的其他方式,可能是您的函数在加载图像之前执行,因此图像第二次从缓存中出现,因此它们不会在第一次加载时花费时间图像没有从缓存中出现。

    $(window).load(function(){
    var imageWidth, totalWidth, sliderContent, $slider;
    $slider = $("#slider");
    sliderContent = $slider.html();
    $slider.html("<div id=\"slideWrapper\">" + sliderContent + "</div>");
    imageWidth = $slider.find("img").width();
    totalWidth = $slider.find("img").size() * imageWidth;
    $("#slider").css("width", imageWidth);
    $("#slideWrapper").css("width", totalWidth);
    // other code .....
    });
    

    希望这是有道理的

    【讨论】:

    • 感谢您的回复。但是 $(window).load() 运行很慢。问题还在继续。
    • 我在第一次加载时明确提到您的图像将加载为新图像,然后浏览器缓存它,因此第二次它们将从缓存中获取并快速加载
    • 当我用 Chrome 和 Safari 打开 html 时遇到这个问题
    • 您可以使用jquery image load event api.jquery.com/load-event 的其他方式查看此
    • 我用 console.log() 检查,imageWidth 和 totalWidth 的值为 0。
    猜你喜欢
    • 2012-02-22
    • 2016-12-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2012-02-27
    • 2023-03-13
    相关资源
    最近更新 更多