2014-09-13 71 views
0

我有一個文本框設置爲我正在製作的JavaScript遊戲的結果輸出。不過,我希望文本框在文本加載到文本框時自動跳下。那可能嗎?動態加載Textarea中的文本,使用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,它覆蓋了JS我曾經爲showResults

+0

添加 「theResults.scrollTop = 9e9;」到你的userGuess()函數的末尾 – dandavis 2014-09-13 22:59:00

回答

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