代码之家  ›  专栏  ›  技术社区  ›  Galen

javascript图像旋转器问题,默认图像

  •  3
  • Galen  · 技术社区  · 16 年前

    我写了一个简单的javascript图像旋转器,它在每次页面加载时随机选取一个图像。问题是,如果我使用默认图像,在javascript加载并替换它之前,该默认图像将显示一秒钟。显然,如果有人禁用了javascript,我希望他们看到一个图像。如何在不闪烁默认图像的情况下拥有默认图像?

    3 回复  |  直到 16 年前
        1
  •  2
  •   Eric Wendelin    16 年前

    听起来您想在window.onload触发之前更改页面html(因为此时默认图像已经显示)。

    您需要将您的javascript函数附加到“domcontentloaded”或通常称为domready事件。迪安·爱德华兹为我们提供了一个出色的跨浏览器实现 http://dean.edwards.name/weblog/2006/06/again/ .

    希望有帮助:)

        2
  •  0
  •   Ates Goral    16 年前

    如果您在页面加载时将默认图像隐藏为第一件事,那么用户可能无法看到该图像。然后您可以在映像上安装一个onload处理程序,并将其源更改为随机映像。加载图像时,可以取消隐藏图像。

    window.onload = function () {
        var img = document.getElementById("rotating_image");
    
        // Hide the default image that's shown to people with no JS
        img.style.visibility = "hidden";
    
        // We'll unhide it when our new image loads
        img.onload = function () {
            img.style.visibility = "visible";
        };
    
        // Load a random image
        img.src = "http://example.com/random" + Math.floor(Math.random() * 5) + ".jpg";
    
    };
    
        3
  •  0
  •   Darryl Hein IrishChieftain    16 年前

    您也可以考虑将JS直接放在图像之后。这可能会在点执行JS,而不是在页面加载时执行。但我不确定。

    <img src="/not/rotated/image.jpg" />
    <script type="text/javascript">
    // change image
    </script>