问题是,当文本区域的高度高于窗口时,滚动条会粘在文本区域的顶部,而文本区域应该聚焦到插入符号所在的位置。
这是我的代码
function adaptiveheight(a) {
$(a).height(0);
var scrollval = $(a)[0].scrollHeight;
$(a).height(scrollval);
}
这是一把小提琴
试着让文本区域变长,你就会发现问题所在。
我尽可能不想要第三方插件。感谢
在adaptiveheight(a)
函数的末尾添加此代码
if (parseInt(a.style.height) > $(window).height() - 30) {
$(document).scrollTop(parseInt(a.style.height));
}
工作演示http://jsfiddle.net/cse_tushar/ve4rL/3/
新Js代码
$("#description").keyup(function (e) {
adaptiveheight(this);
});
i=0;
j=0;
function adaptiveheight(a) {
$(a).height(0);
var scrollval = $(a)[0].scrollHeight;
$(a).height(scrollval);
if (parseInt(a.style.height) > $(window).height()) {
if(j==0){
max=a.selectionEnd;
}
j++;
var i =a.selectionEnd;
console.log(i);
if(i >=max){
$(document).scrollTop(parseInt(a.style.height));
}else{
$(document).scrollTop(0);
}
}
}
工作演示http://jsfiddle.net/cse_tushar/ve4rL/5/
调整文本区域大小后,您可以简单地维护当前页面位置:
function adaptiveheight(a) {
var $a = $(a), $window = $(window), scrollTop = $window.scrollTop();
$a.height(0).height($a.prop('scrollHeight'));
$window.scrollTop(scrollTop);
}
请参阅https://github.com/jgonera/micro.js/blob/master/micro.autosize.js.