动态地将textarea滚动到底部

时间:2014-02-16 16:34:16

标签: javascript textarea scrolltop

我刚开始学习javascript和ajax。我有一个textarea,按下Enter按钮后,它向服务器发送一个请求,返回的内容应该显示在同一个textarea中。虽然我已设法与服务器建立连接,但我无法让textarea在响应后向下滚动。这是我的html文件:

<!DOCTYPE html>
<html>
<script type="text/javascript" src="js/ajax.js"></script>
<body>
<textarea id="myDiv"></textarea>
<script type="text/javascript">

    var terminal = document.getElementById("myDiv");
    console.log(terminal);
    getBrowserDimensions();

    document.getElementById("myDiv").onkeydown = function(event){
        var e = event || window.event;
        if(e.keyCode == 13){
            loadXMLDoc(terminal.value);
        }
    }
</script>
</body>
</html>

这是我的javascript文件:

function loadXMLDoc(sendString){
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHHTP");
    }
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            terminal.value += xmlhttp.responseText+'\n';
        }
    }
    xmlhttp.open("POST", "php/demo_get.php", true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(sendString);
    terminal.scrollTop = terminal.scrollHeight;
    console.log("1: " + terminal.scrollTop);
    console.log("2: " + terminal.scrollHeight);
}

function getBrowserDimensions(){
    var x = window.innerWidth;
    var y = window.innerHeight;
    var terminalWidth = Math.floor(x * 0.95);
    var terminalHeight = Math.floor(y * 0.95);
    terminal.value += "width: " + x + " height: " + y + " tWidth : " + terminalWidth + '\n';
    terminal.style.width = terminalWidth + "px";
    terminal.style.height = terminalHeight + "px";
    terminal.style.resize = "none";
}

我尝试了一些主要在这个网站上找到的方法,如:

terminal.scrollTop = terminal.scrollHeight - terminal.clientHeight;

但没有改变。 textarea将被设置为其可滚动高度的中间位置。即使将scrollTop设置为固定数字(如9999)也不会产生任何不同。我在firefox和chrome中试过这个。我也不应该使用jquery,所以如果对我做错了什么想法,或者建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

ajax调用是异步的,这意味着你正在进行调用,为它完成时创建一个事件处理程序,然后在实际发生之前设置scrollTop值。试试这个......

function loadXMLDoc(sendString){
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHHTP");
    }
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            terminal.value += xmlhttp.responseText+'\n';
            terminal.scrollTop = terminal.scrollHeight;
            console.log("1: " + terminal.scrollTop);
            console.log("2: " + terminal.scrollHeight);
        }
    }
    xmlhttp.open("POST", "php/demo_get.php", true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(sendString);
}