2013-06-18 22 views
2

我試圖爲許多AJAX請求的頁面顯示加載圖像(並將父窗體變爲透明)。什麼是最有效的方式來獨立添加/刪除加載圖標和每個div的不透明度?帶jQuery的模塊化AJAX加載指示器

這是我到目前爲止。我的方法存在的問題是,不透明度也適用於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 

回答

5

我會保持造型的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; 
} 
+0

不錯!這很聰明。出於好奇,你能解釋爲什麼需要將'position:relative;'添加到'.box'嗎? – Justin

+1

需要postion relative,因此可以適當地放置絕對位置元素。如果你刪除你應該看到它破裂。看看[這篇文章](http://css-tricks.com/absolute-positioning-inside-relative-positioning) –

+0

你需要更多upvotes。 –

0

不透明度適用於一個元件的孩子們。而不是使用不透明度,只是使父項的背景對rgba顏色具有更多的不透明性。 Here就是一個例子。你也用上了

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

當你應該做

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

,這是導致頁面崩潰我。

+0

我希望孩子有不透明度降低,以及對節目在AJAX完成之前它們是不活動的。感謝您指出'setTimeout'。我將在我的示例中更新它。另外請注意,除了jsfiddle上的鏈接之外,您應該始終將您的代碼發佈在您的答案中。 – Justin

+0

哦,我不知道這是規則,謝謝! – powerc9000