jQuery 最好的自动增长 textarea 插件是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4952303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best autogrow textarea plugin for jQuery?
提问by Sam Grossberg
There seem to be a ton of really bad autogrow textarea plugins for jQuery. I want my autogrowing text box to be as good as Facebook's. I want it to fit the current line only, and add a line right before it's needed.
似乎有很多非常糟糕的 jQuery 自动增长 textarea 插件。我希望我的自动增长文本框和 Facebook 的一样好。我希望它只适合当前行,并在需要之前添加一行。
Most of the plugins I've reviewed try to guess line height from number of characters, which seems too naive. I've read one solution that creates a hidden div to calculate height. That seems like the right path, but that solution wasn't in plugin form.
我看过的大多数插件都试图从字符数中猜测行高,这似乎太天真了。我已经阅读了一个创建隐藏 div 来计算高度的解决方案。这似乎是正确的路径,但该解决方案不是插件形式。
What's out there that does what I want and is easy to install?
有什么可以满足我的需求并且易于安装?
回答by vantrung -cuncon
Try it. http://www.Hymanlmoore.com/autosizeI thing here's the best. It's a very good one.
尝试一下。http://www.Hymanlmoore.com/autosize我觉得这里是最好的。这是一个非常好的。
回答by Chris Laplante
I have a plugin that calculates just that: http://www.mostthingsweb.com/2012/01/textarea-line-count-version-1-3-released/. It uses the hidden div approach, and even matches the correct font attributes. Check it out :)
我有一个插件可以计算:http: //www.mostthingsweb.com/2012/01/textarea-line-count-version-1-3-released/。它使用隐藏的 div 方法,甚至匹配正确的字体属性。一探究竟 :)
You could invoke the plugin every time a user hits a key in the textbox, and then resize the textbox accordingly. Maybe even every other key, if you want to not hog processing power.
每次用户点击文本框中的键时,您都可以调用该插件,然后相应地调整文本框的大小。如果您不想消耗处理能力,甚至可能是所有其他键。
回答by Chris Laplante
hey this is pure javascript
嘿,这是纯 javascript
function sz(t) {
dv = document.createElement("div");
dv.style.visibility="hidden";
dv.style.position="absolute";
dv.style.width=t.offsetWidth;
dv.innerHTML = t.value.replace(/\n/g, "<br>");
document.body.appendChild(dv);
t.style.height=(dv.offsetHeight+22)+"px";
dv.parentNode.removeChild(dv);
}
then you just use onkeyup="sz(this)"
那么你只需使用 onkeyup="sz(this)"