Textarea中的动态加载文本,使用Javascript自动向下滚动?

时间:2014-09-13 19:19:29

标签: javascript

我有一个文本框设置为我正在制作的JavaScript游戏的结果输出。但是,我希望文本框在文本加载到文本框时自动跳转。那可能吗?

HTML

<fieldset class="theResults" id="theResults">
<label>Your past guesses:</label> 
<textarea class="form-control input-lg" id="showResults" name="showResults" rows="1">
</textarea>
</fieldset>

JS

function userGuess() {
  var nGuess = document.getElementById("nGuess").value;
  var theResults = document.getElementById("showResults");

  if (nGuess == numToGuess) {
    theResults.value = theResults.value + "\r" + "Congratulations, that is right! You guessed " + nGuess + ".";
  } else if (nGuess > numToGuess) {
    theResults.value = theResults.value + "\r" + "Try something lower, that is too high! You guessed " + nGuess + ".";
  } else {
    theResults.value = theResults.value + "\r" + "Whoops, that is too low, try again! You guessed " + nGuess + ".";
  }
}

我尝试使用scrollTop并覆盖了我对showResults的JS。

1 个答案:

答案 0 :(得分:1)

您需要先向rowscols提供TextArea,首先,您只会看到one行文字。

<textarea class="form-control input-lg" id="showResults" name="showResults" rows="5" cols="40">

然后您可以使用theResults.scrollTop = theResults.scrollHeight;

在底部设置文字

完整代码:

function userGuess() {
        var numToGuess = 55; //suppose number to guess is 55
        var nGuess = document.getElementById("nGuess").value;
        var theResults = document.getElementById("showResults");
        if (nGuess == numToGuess) {
            theResults.value = theResults.value + "\r" + "Congratulations, that is right! You guessed " + nGuess + ".";
        } else if (nGuess > numToGuess) {
            theResults.value = theResults.value + "\r" + "Try something lower, that is too high! You guessed " + nGuess + ".";
        } else {
            theResults.value = theResults.value + "\r" + "Whoops, that is too low, try again! You guessed " + nGuess + ".";
        }
        theResults.scrollTop = theResults.scrollHeight; //auto scroll for text
    }

<强> DEMO