Javascript错误加载图像淡入

标签 javascript jquery

我的脚本出现不一致错误。通常一切正常,但是,我时不时会收到以下错误:ReferenceError: fadeIn is not defined

相关代码如下:

<head>

    <script type="text/javascript" charset="utf-8">
        window.fadeIn = function(obj) {
            var item = $(obj).parent();
            item.fadeIn(1000);
        }
    </script>

<body>

 <div class="item" style="display:none"><img onload="fadeIn(this)" src="/uploads/thumbs/{{image.url}}"><br>{{ image.description }}</div>

同样,大部分时间图像都在加载和淡入淡出,但有时我会收到错误,图像不会淡入。

有没有更好的方法来解决这个问题?或者只是我缺少的东西?

最佳答案

您需要确保在 DOM 准备好后加载您的代码。

window.onload = function(){
    var fadeIn = function(obj) {
         var item = $(obj).parent();
         item.fadeIn(1000);
    };
};

...这是一个部分修复,但不是真的,因为很可能,您的 <img/>将 onload 硬编码到其中的标签将尝试在该方法可用之前触发该方法。

既然你无论如何都在使用 jQuery,你应该看看这样的东西:

$(function() {
    $(".item img").load(function(){
         $(this).fadeIn(1000);
    });
});

并从您的 img 标签中删除硬编码的 onload。

还应注意,.load() API 页面上列出了警告:

来自文档 (http://api.jquery.com/load-event/):

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

It doesn't work consistently nor reliably cross-browser It doesn't fire correctly in WebKit if the image src is set to the same src as before It doesn't correctly bubble up the DOM tree Can cease to fire for images that already live in the browser's cache

更好的解决方案可能是使用 CSS 隐藏图像,然后在触发加载事件后,将它们淡入。

(甚至更好的方法可能是让浏览器行为正常,因为您的结果可能是混合的,并且看到空白页面的用户可能会认为他们的浏览器出现故障,在您的动画完成之前点击重新加载按钮。......只是一个友好的警告,这些类型的 DOM 操作有时会对用户行为产生意想不到的副作用!)

关于Javascript错误加载图像淡入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13259121/

相关文章:

javascript - 如何在失败的ajax post请求上恢复可拖动元素

javascript - 如何动态缩放svg

javascript - Nodejs POST 请求未发布到数据库并返回 302 响应

javascript - new YT.Player() 正在开发中,但不在生产中

javascript - DOM 是否使用 jQuery 立即刷新?

jquery - jQuery 的 CSS3 文本阴影效果

javascript - 如何使用JS搜索表并仅返回匹配的行?

javascript - 动态创建列表的 this 选择器也引用父级

javascript - 当我选中复选框时如何将值 text1 复制到 text2?

javascript - jquery 中最接近的值四舍五入?