如何在自动调整textarea中键入时停止窗口跳转 [英] How to stop window jumping when typing in autoresizing textarea

查看:112
本文介绍了如何在自动调整textarea中键入时停止窗口跳转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个问题以构建一个文本区域,该文本区域在文本溢出时垂直扩展:

I am using the accepted answer to this question to build a textarea that expands vertically as text overflows:

<!DOCTYPE html>
<html>
<head>
<title>autoresizing textarea</title>
<style type="text/css">
textarea {
 border: 0 none white;
 overflow: hidden;
 padding: 0;
 outline: none;
 background-color: #D0D0D0;
 resize: none;
}
</style>
<script type="text/javascript">
var observe;
if (window.attachEvent) {
 observe = function (element, event, handler) {
  element.attachEvent('on'+event, handler);
 };
}
else {
 observe = function (element, event, handler) {
  element.addEventListener(event, handler, false);
 };
}
function init () {
 var text = document.getElementById('text');
 function resize () {
  text.style.height = 'auto';
  text.style.height = text.scrollHeight+'px';
 }
 /* 0-timeout to get the already changed text */
 function delayedResize () {
  window.setTimeout(resize, 0);
 }
 observe(text, 'change',  resize);
 observe(text, 'cut',     delayedResize);
 observe(text, 'paste',   delayedResize);
 observe(text, 'drop',    delayedResize);
 observe(text, 'keydown', delayedResize);

 text.focus();
 text.select();
 resize();
}
</script>
</head>
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>

在textarea的大小长于浏览器窗口之前,它一直运行良好。此时,每按一次键,窗口顶部就会跳到文本区域的顶部。你能帮助我理解为什么以及如何解决这个问题吗?

It works well until the size of the textarea grows longer than the browser window. At that point the top of the window jumps to the top of the textarea every time a key is pressed. Can you help me understand why and how to fix it?

一个理想的解决办法就是让页面完全无法移动。但是如果将页面底部绑在textarea的底部更容易,那也会更有效。

An ideal fix would be to keep the page from moving at all. But if it's easier to keep the bottom of the page tied to the bottom of the textarea, that would work too.

我在Firefox 21.0和Chrome 28.0中遇到此问题: http://jsfiddle.net/CbqFv/

I am having this issue in Firefox 21.0 and Chrome 28.0: http://jsfiddle.net/CbqFv/

推荐答案

保存 scrollLeft scrollTop 值,然后将其还原调整textarea的大小后:

Save the scrollLeft, scrollTop values, and then restore them after resizing the textarea:

function resize () {
   var scrollLeft = window.pageXOffset ||
   (document.documentElement || document.body.parentNode || document.body).scrollLeft;

   var scrollTop  = window.pageYOffset ||
   (document.documentElement || document.body.parentNode || document.body).scrollTop;

   text.style.height = "auto";
   text.style.height = text.scrollHeight + 'px';

   window.scrollTo(scrollLeft, scrollTop);
}

JSFiddle: http://jsfiddle.net/losnir/nnkeH/1

JSFiddle: http://jsfiddle.net/losnir/nnkeH/1

这篇关于如何在自动调整textarea中键入时停止窗口跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆