Add text to the bottom of a div (or another element) - emulating chat console

前端 未结 3 1087
北恋
北恋 2021-01-06 12:42

I have a div that should be collecting text as text is entered into the input box (right now it just reproduces the input, but later it should produce semi-intelligent respo

3条回答
  •  难免孤独
    2021-01-06 13:21

    I would use a different way to solve this problem. Maybe I'm wrong but it sounds like you want to emulate a chat console, displaying the text lines in reverse order. In that case I would use UL/LI structure wrapped around a DIV; somehow I believe this is the fastest way since we don't care about the previous lines - we just append the new ones, adding another LI to the end of the UL element. Check the snippet out

    // JavaScript - Tested on IE11, Firefox, Chrome, Opera and Safari
    window.onload = function(){
        var div = document.getElementById("wrapper"),
            ul = document.getElementById("list"),
            input = document.getElementById("text"),
            flag = false, 
            li;
        input.onkeypress = function(e){
            e = e || window.event;
            var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
            if (charCode == 13) {
                li = document.createElement("LI");      
                li.innerHTML = input.value;
                ul.appendChild(li);
                li.scrollIntoView();
                if(ul.offsetHeight >= div.offsetHeight && flag !== true){
                    ul.style.height = div.offsetHeight + "px";
                    flag = true;
                }
                document.getElementById("text").value = "";
            }   
        };
    };
    
    /* CSS */
    #wrapper {
        position:relative; height:200px; width:300px; background-color:#fff;
    }  
    #list {
        margin:0px; padding:0px; position:absolute; bottom:0px; left:0px; width:inherit; overflow:hidden; overflow-y:scroll;
    }
    #text { 
        width:300px; 
    }
    
    
    

      Check the working jsBin (on Firefox, Chrome, Opera and Safari) or jsFiddle (on IE11)

    提交回复
    热议问题