2013-04-12 87 views
0

所以我想要完成的事情看起來像簡單的CSS等我正在改變一個消息系統和什麼對話開始在底部像Facebook或文本消息它有一個左邊的人和右邊的人。從容器底部開始內容並向上推

當通過ajax添加新內容時,我該如何獲得divs?我看到這similar question,但不太明白他的意思是什麼意思。一個例子會很棒。

回答

0

也許這樣的事情?

<!DOCTYPE html> 
<html> 
<head> 
<script> 
function byId(e){return document.getElementById(e);} 
function newEl(tag){return document.createElement(tag);} 
function newTxt(txt){return document.createTextNode(txt);} 
function prependChild(parent, element) 
{ 
    if (parent.childNodes) 
     parent.insertBefore(element, parent.childNodes[0]); 
    else 
     parent.appendChild(element) 
} 


window.addEventListener('load', mInit, false); 

function mInit() 
{ 
    byId('btnAddNew').addEventListener('click', onAddBtnClicked, false); 
} 

function onAddBtnClicked() 
{ 
    var txtInputElem = byId('newMsgTxtInput'); 
    var msgTxt = txtInputElem.value; 

    var li = newEl('li'); 
    li.appendChild(newTxt(msgTxt)); 

    var ulTgt = byId('msgTarget'); 

    var existingLiItems = ulTgt.querySelectorAll('li'); 
    var numItemsExisting = existingLiItems.length; 
    if (numItemsExisting%2 != 0) 
     li.className = 'even'; 
    else 
     li.className = 'odd'; 

    prependChild(ulTgt, li); 
} 

</script> 
<style> 
.controls 
{ 
    display: inline-block; 
    padding: 8px; 
    margin: 8px; 
    border: solid 1px #555; 
    border-radius: 4px; 
    color: #777; 
    background-color: #ddd; 
} 
#msgTarget 
{ 
    width: 275px; 
    border: solid 1px #555; 
    margin: 8px; 
    border-radius: 4px; 
} 

/* 
Doesn't work 'properly' - since we add items at the top, rather than the bottom 
The first item added will be 'even', then the second item gets added and now it's the first child 'even' 
so, the item added first is now an 'odd' child. A better way may be to count the number of existing li 
items the ul contains, before assigning the new li elements a class of even or odd that will enable css 
styling. 
#msgTarget li:nth-child(odd) 
{ 
    background-color: #CCC; 
} 
#msgTarget li:nth-child(even) 
{ 
    background-color: #5C5; 
} 
*/ 

.odd 
{ 
    background-color: #CCC; 
} 
.even 
{ 
    background-color: #5C5; 
} 

</style> 
</head> 
<body> 
    <div class='dlg'> 
     <div class='controls'> 
      <input id='newMsgTxtInput'/><button id='btnAddNew'>Add message</button> 
     </div> 
     <ul id='msgTarget'></ul> 
    </div> 
</body> 
</html> 
+0

感謝您的幫助,我找到了一種方法來做到這一點,我喜歡確定。 –