2012-06-14 32 views
0

在我的應用程序中,我想在用戶完成某些操作時在屏幕中間顯示一些信息。 (就像閃光消息)將元素設置在指定容器的中間

現在,我創建了一個功能,使這個:

var createFlashMessage = function(message, parentDom, time) { 
     parentDom = $(parentDom); 
     var mask = parentDom.children().first(); 
     if(!mask.is('message-mask')) { 
      mask = $('<div>').addClass('message-mask'); 
      mask.hide().appendTo(parentDom); 
     } 
     var messageSpan = $('<span>').html(message).appendTo(mask); 
     var conWidth = parentDom.width(), conHeight = parentDom.height(); 
     messageSpan.css({ 
      left:Math.floor(conWidth/2-messageSpan.width()/2), 
      top:Math.floor(conHeight/2-messageSpan.height()/2) 
     }).fadeIn(500,function() { 
      $(this).delay(time || 3000).fadeOut(); 
     }); 
    }; 

這是面膜DIV CSS樣式:


.message-mask 
{ 
    position: relative; 
    width: 100%; 
    height: 100%; 
    overflow: hidden; 
} 

然而,當我運行它,我發現面具div不能被容器放在正確的位置。

如何製作它?

回答

0

增加您彈出的z-index,使其float-left,那麼你可以這樣做:

messageSpan.css('margin-left', ((conWidth - messageSpan.width())/2)); 
messageSpan.css('margin-top', ((conHeight - messageSpan.height())/2)); 

另外,mesage面膜應該更喜歡這個:

.message-mask { 
    position:fixed; 
    display: none; 
    width: 100%; 
    height: 100%; 
    left:0px; 
    top:0px; 
    z-index: 9998; 
} 

然後,當您顯示彈出窗口時,您可以取消隱藏背景。

+0

固定位置無法工作,它基於整個窗口而不是指定的元素。 – hguser

+0

我不認爲它很重要,因爲面具仍然會覆蓋您的所有屏幕。我認爲你遇到的問題是你的.message-mask div沒有插入正確的位置。嘗試在標籤後面插入mask元素,以便它可以固定並覆蓋整個屏幕。 – GEMI

0

不確定,因爲我更喜歡C#的人,但我認爲它應該更像這樣。

 left:Math.floor((conWidth/2)-(messageSpan.width() /2)), 
     top:Math.floor((conHeight/2)-(messageSpan.height() /2)) 
0

嘗試,

.message-mask 
{ 
    position: absolute; 
    width: 100%; 
    height: 100%; 
    overflow: hidden; 
}