2013-10-25 37 views
2

我已经写了一个带有文本区域,文本框和按钮的HTML表单。无论我在文本框中输入的内容都将被添加到textarea,当点击按钮时。现在,我的问题是当文本区域被完全填满时,新到达的文本出现在底部,我必须手动向下滚动才能查看此文本。是否有任何JavaScript的方法,使到达的文本可见始终没有向下滚动...请帮助如何给自动滚动文本区

+0

这可以通过JavaScript来实现或jQuery的浏览器不知道要查看本文 –

+0

的可能的复制[如何有textarea在更新时保持滚动到底部](https://stackoverflow.com/questions/7373081/how-to-have-a-textarea-to-keep-scrolled-to-the-bottom-when-updated) – LoganMzz

回答

0

这个例子随着内容的文本添加textarea的大小;

Example

的Javascript

var txt = $('#comments'), 
    hiddenDiv = $(document.createElement('div')), 
    content = null; 

txt.addClass('txtstuff'); 
hiddenDiv.addClass('hiddendiv common'); 

$('body').append(hiddenDiv); 

txt.on('input', function() { 

    content = $(this).val(); 

    content = content.replace(/\n/g, '<br>'); 
    hiddenDiv.html(content + '<br class="lbr">'); 

    $(this).css('height', hiddenDiv.height()); 

}); 

txt.trigger('input'); 

CSS

body { 
    margin: 20px; 
} 

p { 
    margin-bottom: 14px; 
} 

textarea { 
    color: #444; 
    padding: 5px; 
} 

.txtstuff { 
    resize: none; /* remove this if you want the user to be able to resize it in modern browsers */ 
    overflow: hidden; 
} 

.hiddendiv { 
    display: none; 
    white-space: pre-wrap; 
    word-wrap: break-word; 
    overflow-wrap: break-word; /* future version of deprecated 'word-wrap' */ 
} 

/* the styles for 'commmon' are applied to both the textarea and the hidden clone */ 
/* these must be the same for both */ 
.common { 
    width: 500px; 
    min-height: 50px; 
    font-family: Arial, sans-serif; 
    font-size: 13px; 
    overflow: hidden; 
} 

.lbr { 
    line-height: 3px; 
} 
0

对于具有文本区域自动滚动功能,在结尾处添加这段代码在任何你正在尝试参加来自文本框的内容:

var console = $('#area'); 
console.scrollTop(
console[0].scrollHeight - console.height()); 

DEMO

希望这有助于:)