0

所以我想要完成的似乎是简单的 CSS 等。我正在更改一个消息传递系统,以及从底部开始的对话有点像 Facebook 或文本消息,其中一个人在左边,另一个人在右边。

当通过 ajax 添加新内容时,如何让 div 上升?我看到了这个类似的问题,但不太明白他的意思是专注于 LI。一个例子会很棒。

4

1 回答 1

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>
于 2013-04-12T10:11:16.720 回答