2014-02-19 32 views
1

我想顯示一個垂直和水平居中的div,這個工作正常,但是當我向下滾動頁面並嘗試底部鏈接時(這是一條評論框),然後它會顯示在頁面的頂部,而不是在屏幕上,您需要向上滾動才能使用它。即使用戶向下滾動,我怎樣才能讓它居中?中心div垂直和水平中心,即使當頁面向下滾動時

這裏是我到目前爲止的代碼(從研究,我做了):

$("#comment").css('top', ((screen.height/2) - ($('#comment').height()/2))+'px'); 
$("#comment").css('left', (screen.width/2) - ($('#comment').width()/2)+'px'); 

在此先感謝!

+1

使用'位置:fixed',而不是絕對的 – Pete

回答

2

你需要通過jQuery來做到這一點? 也許你可以只是CSS樣式嗎?

CSS

#commentBox { 
    position:fixed; 
    top:0; 
    bottom:0; 
    left:0; 
    right:0; 
    margin:auto; 
    height:240px; 
    width:70%; 
    padding:15px; 
    border:1px dashed #333; 
    background-color:#eee; 
} 

看我的例子:FIDDLE

+0

出色答卷:-) –

0

.scroll()

var comment = $("#comment"), 
    com = $('#com'); 
$(window).scroll(function() { 
    comment.css('top', ((screen.height/2) - (com.height()/2)) + 'px'); 
    comment.css('left', (screen.width/2) - (com.width()/2) + 'px'); 
}); 
+0

不幸的是我仍然得到同樣的問題 – user3241507