【问题标题】:Modular AJAX loading indicator with jQuery带有 jQ​​uery 的模块化 AJAX 加载指示器
【发布时间】:2013-06-18 19:30:13
【问题描述】:

我正在尝试为包含许多 AJAX 请求的页面显示加载图像(并将父级变为透明)。分别为每个 div 添加/删除加载图标和不透明度的最有效方法是什么?

这是我目前所拥有的。我的方法的问题是不透明度也适用于 gif,这不是我想要的。我的代码是否有简单的修复方法或更好的方法?

示例:http://jsfiddle.net/justincook/x4C2t/

HTML:

<div id="a" class="box">A</div>
<div id="b" class="box">B</div>
<div id="c" class="box">C</div>

JavaScript:

$.fn.loading = function(show){
    if(show){
        this.prepend('<div class="loading-centered"></div>');
        this.css({ opacity: 0.3 });
    }else{
        this.children('.loading-centered').remove();
        this.css({ opacity: 1 });
    }
};

$('#a').loading(true); //start  
setTimeout(function(){ $('#a').loading(false); }, 3000); // stop

【问题讨论】:

    标签: javascript jquery ajax css


    【解决方案1】:

    我会将样式保留在 CSS 中,只使用 JS 注入/删除元素 http://jsfiddle.net/x4C2t/7/

    $.fn.loading = function(show){
        if(show){
            this.prepend('<div class="loading-centered"></div>');
        }else{
            this.children('.loading-centered').remove();
        }
    };
    

    css:

    .box {
        float:left;
        width:100px;
        height:100px;
        border:1px solid #bbb;
        margin: 10px;
        padding:20px;
        text-align:center;
        border-radius:10px;
        background: #eee;    
        position: relative;
    }
    
    .loading-centered {
        background:url('http://www.ajaxload.info/images/exemples/24.gif') center center no-repeat white;
        position:absolute;
        height: 100%;
        width: 100%;
        top: 0;
        left: 0;
        border-radius:10px;
        zoom: 1;
        filter: alpha(opacity=50);
        opacity: 0.5;
    }
    

    【讨论】:

    • 不错!这很聪明。出于好奇,您能解释一下为什么需要将position:relative; 添加到.box 吗?
    • postion relative 是必需的,因此可以适当地放置绝对位置元素。如果你删除你应该看到它打破。查看this article
    【解决方案2】:

    不透明度也适用于子元素。而不是使用不透明度,只需使用 rgba 颜色使父级的背景具有更多的不透明度。 Here 就是一个例子。你也在使用

    setInterval(function(){ $('#a').loading(false); }, 3000);
    

    你应该什么时候完成

    setTimeout(function(){ $('#a').loading(false); }, 3000);
    

    这导致我的页面崩溃。

    【讨论】:

    • 我希望孩子们也降低不透明度,以表明他们在 AJAX 完成之前处于非活动状态。感谢您指出setTimeout。我将在我的示例中更新它。另请注意,除了 jsfiddle 上的链接之外,您还应始终在答案中发布您的代码。
    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2010-10-09
    • 2015-03-20
    • 2016-03-06
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多