【问题标题】:Large images prevent div from fading in大图像可防止 div 淡入
【发布时间】:2012-08-17 13:28:02
【问题描述】:

我有这个设置:

<div id="container1">
    <!-- content from one section -->
</div>
<div id="container2" style="display:none;">
    <div id="sub-container">
        <img src="image1.png" />
        <img src="image2.png" />
        <!-- 20 or so images sit here -->
    </div>
</div>

container1 最初显示。在 document.ready 上,除了前四个图像之外的所有图像都被隐藏起来,以便构建一个旋转木马。 用户点击一个按钮,container1 淡出,container2 淡入。

用户第一次单击按钮时,container2 不会淡入,而是直接跳转到可见状态。第二次,淡入正常工作。

所涉及的图像相当可观(总大小约为 10MB),但这不是问题,因为该页面旨在在本地查看。如果我有一个或两个图像,问题就不会出现这一事实告诉我,浏览器正在努力同时加载图像和淡入。第二次加载时,图像已被缓存并正常淡入。

我尝试了这样的预加载形式:

/* take the div outside the viewport but still render it */
.hide {
    position: absolute;
    top: -9999px;
    left: -9999px;
}

var cacheContainer = "<div class='hide'></div>",
    $images = $("#sub-container img");
// move the images to the container
$(cacheContainer).appendTo("body").append($images);

// hopefully 500ms would be enough for the images to render?
setTimeout(function () {
    images.appendTo("#sub-container");
    doGallery(); // build carousel
},500);

...然而这会导致同样的问题 - container2 第一次弹出而不是消失,之后工作得很好。

有什么想法吗?


根据要求,这是我用来隐藏/显示容器的方法:

$(document).ready(function() {
    var $currentTab = $("#container1"),
        $newTab,
        newTabName;

    // a couple of more unrelated setting up functions go here

    doImageCaching(); // the function I've got above

    $("#container2").hide();

    $("#tab-links>a").click(function(e) {
        e.preventDefault();

        // probably a bit cheeky doing it this way but oh well
        newTabName = $(this).attr("id").replace("-btn", "");
        if($currentTab.attr("id") === newTabName) {
            return;
        }
        $newTab = $("#" + newTabName);

        $newTab.stop(true, true).fadeToggle(200);
        $currentTab.stop(true, true).delay(100).fadeToggle(200);
        $currentTab = $newTab;
        $newTab = null;
    });
});

这里是#tab-links供参考:

<div id="tab-links">
    <a id="container1-btn" href="#">show container 1</a>
    <a id="container2-btn" href="#">show container 2</a>
</div>

编辑 2 所以我刚刚注意到一些新的东西:所以我第二次切换到 container2 时它会正常淡入。如果我等待 10 秒左右,然后尝试切换到 container2再次,问题再次出现。

所以在我看来,加载 DOM 与此无关,我正在处理 Chrome 的内部存储器。因此它会加载图像,然后在它们再次隐藏时“忘记”它们。哎呀。

是否有人对如何防止浏览器“忘记”图像有任何想法,或者这是我不应该采取的方向?

【问题讨论】:

  • doGallery 是做什么的?它适用于较小的图像吗?
  • doGallery 做了很多事情,包括遍历每个大图像,更改它们的位置,隐藏除前四个之外的所有图像,添加一些事件侦听器等。这些都是在用户单击淡入淡出的按钮container2
  • 我不确定是否值得一提,但无论如何我都会这样做 - 图像都缩小到其可见尺寸的三分之一左右(使用 heightwidth in标记),并且仅在稍后单击它们时展开。
  • 是的,向我们展示在图像中消失的代码。
  • 更新了我的问题,见上文。

标签: javascript jquery image


【解决方案1】:

所以我最终将我的超高质量 PNG 转换为超高质量 JPG - 这导致文件大小减少了大约 20-30%,而外观质量几乎没有任何降低。我的问题也消失了。

这个故事的寓意是:即使您正在开发一个不上线的页面,您仍然需要优化您的图像。

感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多