2012-03-03 73 views
0

我想在每次在我的數據庫中找到新用戶時插入一個新的div。如果我更改CSS(從類中刪除「bottom」和「absolute」),我有以下代碼工作。問題在於它從頂部開始,每個div插入到前一個下面。我想讓div位於屏幕的左下角,然後在插入新div時向上移動。它基本上會推動現有的divs,而最新的div將會處於最底層。任何想法如何做到這一點?任何幫助,將不勝感激。謝謝!頁面底部的動態div-Javascript

此代碼將插入一個新的div,但它只是將它放在前一個之上。

.greyBox { 
    padding:8px; 
    background: grey; 
    margin-bottom:8px; 
    width:200px; 
    height:50px; 
    bottom:0; 
    position:absolute; 
} 
.redBox { 
    padding:8px; 
    background: red; 
    margin-bottom:8px; 
    width:200px; 
    height:25px; 
    bottom:1; 
    position:absolute; 
} 

<p> 
    <button id="after">New User</button> 
    <button id="reset">reset</button> 
</p> 

<div class="greyBox">Users</div> 

$("#after").click(function() { 
    $('.greyBox').after("<div class='redBox'>User 1</div>"); 
}); 

$("#reset").click(function() { 
    location.reload(); 
}); 

http://jsfiddle.net/ymTtB/

回答

1

添加一個新的帶有「底部」類的div容器 http://jsfiddle.net/4np4q/

<html> 
<head> 
<script type="text/javascript" src="jquery.js"></script> 

<style type="text/css"> 
    .bottom{ 
    position: absolute; 
    bottom: 0;  
    } 
    .greyBox{ 
     padding:8px; 
     background: grey; 
     margin-bottom:8px; 
     width:200px; 
     height:50px; 

    } 

    .redBox{ 
     padding:8px; 
     background: red; 
     margin-bottom:8px; 
     width:200px; 
     height:25px; 
    } 
</style> 

</head> 
<body> 

    <p> 
    <button id="after">New User</button> 
    <button id="reset">reset</button> 
    </p> 

    <div class="bottom"> 
    <div class="greyBox">Users</div> 
</div> 
<script type="text/javascript"> 

    $("#after").click(function() { 
     $('.greyBox').after("<div class='redBox'>User 1</div>"); 
    }); 

    $("#reset").click(function() { 
     location.reload(); 
    }); 

</script> 
</body> 
</html> 
+0

工作就像一個魅力。謝謝! – mkyong 2012-03-03 15:31:10

+0

我用這個作爲例子,我將需要消除按鈕,因爲div將自動創建。我怎樣才能改變這個能夠傳遞參數。我想我想讓它成爲一個單獨的函數,可以從程序中調用,而不是點擊。 – mkyong 2012-03-03 15:37:07

0

這是你position: absolute.redbox

.greyBox { 
    padding:8px; 
    background: grey; 
    margin-bottom:8px; 
    width:200px; 
    bottom:0; 
    position:absolute; 
} 

.redBox { 
    padding:8px; 
    background: red; 
    margin-bottom:8px; 
    width:200px; 
    height:25px; 
} 

而且,我以爲你試圖添加到.greyBox元素,而不是後。

$("#after").click(function() { 
    $('.greyBox').append("<div class='redBox'>User 1</div>"); 
}); 

$("#reset").click(function() { 
    $('.greyBox').children().remove(); 
}); 

http://jsfiddle.net/Bb6am/

如果你確實想.after()greyBox,你需要使用包裝和應用 「底」 的風格吧:

.users { 
    width:200px; 
    bottom:0; 
    position:absolute; 
} 
.greyBox { 
    padding:8px; 
    background: grey; 
    margin-bottom:8px; 
} 

<p> 
    <button id="after">New User</button> 
    <button id="reset">reset</button> 
</p> 

$("#after").click(function() { 
    $('.greyBox').after("<div class='redBox'>User 1</div>"); 
}); 

$("#reset").click(function() { 
    $('.users').children().not('.greyBox').remove(); 
}); 

http://jsfiddle.net/Bb6am/2/