javascript jQuery / JS 获取 textarea 的滚动条高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5980150/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:01:09  来源:igfitidea点击:

jQuery / JS get the scrollbar height of an textarea

javascriptjquerytextareascrollbar

提问by iWeb

I've got a textarea with a fixed height. When the user types text into the textarea a scrollbar will show up after the user typed some text in it.

我有一个固定高度的文本区域。当用户在 textarea 中键入文本时,会在用户在其中键入一些文本后显示滚动条。

How can I get the scrollbar height using jQuery or plain JavaScript? I've been searching for this for hours, but couldn't find anything. I can't just insert a div and get the scrollbar height via the div offset because a textarea is not allowed to have child elements.

如何使用 jQuery 或纯 JavaScript 获取滚动条高度?我一直在寻找这个数小时,但找不到任何东西。我不能只插入一个 div 并通过 div 偏移量获取滚动条高度,因为 textarea 不允许有子元素。

Please don't give me a link to a jQuery Plug-In that does the job. I want to learn something.

请不要给我一个链接到一个 jQuery 插件来完成这项工作。我想学点东西。

回答by kennebec

textarea.scrollHeight

returns an integer (pixels)

返回一个整数(像素)

回答by Kashyap Makadia

$.each($("textarea"), function () {
    var scrollHeight = parseInt(this.scrollHeight);
    if ($("this").val() != "" && isNaN(scrollHeight) == false && scrollHeight > 0 && scrollHeight > $(this).height()) {
        console.log($(this).attr("id"));
        $(this).height(scrollHeight);
    }
});

回答by Akash gupta

Please note that you should exclude the upper paddingand the lower paddingof the textarea while comparing the scrollHeight.

请注意,在比较 scrollHeight 时,您应该排除textarea的上边距下边距

Example

例子

var scrollHeight = $("#textarea_id")[0].scrollHeight;
var padding = 14; //upperpadding 7 and lower padding 7.

if($("#textarea_id")[0].height() < (scrollHeight - padding)) {
  $("#textarea_id")[0].height(scrollHeight - padding);
}