2012-03-08 209 views
4

我在嘗試爲textarea設置scrollTop值時遇到了問題。我的JavaScript代碼如下 -如何設置textarea的scrollTop值?

var element = document.getElementById("messageTextArea"); 
console.log("scrollTop = "+element.scrollTop); 
console.log("scrollHeight = "+element.scrollHeight); 
element.scrollTop = element.scrollHeight; // doesn't work! 

console.log("The value is-->"+element.scrollTop); // no change! 

element = document.getElementById("messageTextArea"); 
console.log("Now scrollTop = "+element.scrollTop);   // no change! 
console.log("Now scrollHeight = "+element.scrollHeight); 

Firefox的控制檯日誌提供了以下 -

scrollTop = 0 
scrollHeight = 86 
The value is-->0 
Now scrollTop = 0 
Now scrollHeight = 86 

我真正想要做的是使textarea的莫名其妙自動向下滾動到最大時,文字不符合實際的寬度和高度,滾動條被激活。

下面的兩個截圖說明問題 -

這是我目前 -

enter image description here

這是我想擁有的東西 -

enter image description here

請幫忙!

+0

你試過['.scrollIntoView'](https://developer.mozilla.org/ EN/DOM/element.scrollIntoView)? – 2012-03-08 21:31:32

+0

@GGG我試過element.scrollIntoView(false),但它仍然沒有工作。 :( – CodeBlue 2012-03-08 21:36:48

+0

它應該工作,如果你將它稱爲一個元素,你追加到聊天記錄的底部。 – 2012-03-08 21:44:03

回答

1

好吧,對不起,夥計們。問題在於我收到了錯誤的文本區域。這太尷尬了!現在它可以工作。

var element = document.getElementById("chatTextArea"); // <-- this is where I was making a mistake in my code. So embarrassing! 
0

也有問題,在使用火狐scrollToptextarea,特別是如果textarea的值設置與AJAX。

這爲我工作:

<script> 
function scroll_bottom(elm){ 
    var elm = document.getElementById(elm); 
    var bottom = function() { 
     elm.scrollTop = elm.scrollHeight; 
    }; 
    setTimeout(bottom, 0); 
} 
</script> 

然後使用它,例如:

<textarea id="log" style="width:100%;height:100%;resize:none;"></textarea> 

<script> 
$(document).ready(function(){ 
    scroll_bottom('log'); 
}); 
</script>