Javascript 检测文本区域中的滚动条

发布于 2024-09-09 11:09:53 字数 109 浏览 9 评论 0原文

我想知道是否有人知道我将如何检测滚动条何时出现在 textarea 内。

我目前在 JavaScript 中使用 mootools,但在让它检测滚动条时遇到问题。

I was wondering if anybody knows how I would go about detecting when the scrollbar appears inside a textarea.

I am currently using mootools for my JavaScript and I am having issues getting it to detect a scrollbar.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雨巷深深 2024-09-16 11:09:53
function has_scrollbar(elem_id)
{
    const elem = document.getElementById(elem_id);
    if (elem.clientHeight < elem.scrollHeight)
        alert("The element has a vertical scrollbar!");
    else
        alert("The element doesn't have a vertical scrollbar.");
}

请参阅此 jsFiddle http://jsfiddle.net/qKNXH/

function has_scrollbar(elem_id)
{
    const elem = document.getElementById(elem_id);
    if (elem.clientHeight < elem.scrollHeight)
        alert("The element has a vertical scrollbar!");
    else
        alert("The element doesn't have a vertical scrollbar.");
}

See this jsFiddle http://jsfiddle.net/qKNXH/

享受孤独 2024-09-16 11:09:53

我制作了 Tommaso Taruffis 代码的 jQuery“兼容”版本

function resize_until_scrollbar_is_gone(selector) { 
    $.each($(selector), function(i, elem) {
        while (elem.clientHeight < elem.scrollHeight) {
            $(elem).height($(elem).height()+5);
        }
    });
}

它可以处理多个元素并接受:选择器、jQuery 对象或DOM 元素。

可以这样调用:

resize_until_scrollbar_is_gone('textarea');

I made a jQuery "compatible" version of Tommaso Taruffis code

function resize_until_scrollbar_is_gone(selector) { 
    $.each($(selector), function(i, elem) {
        while (elem.clientHeight < elem.scrollHeight) {
            $(elem).height($(elem).height()+5);
        }
    });
}

It can handle multiple elements and accepts: selectors, jQuery objects, or DOM elements.

It can be called like this:

resize_until_scrollbar_is_gone('textarea');
红ご颜醉 2024-09-16 11:09:53

即使在文本区域中,托马索的解决方案也能完美运行。但是,如果用户要在文本区域中键入内容,并且突然文本区域给自己一个滚动条,您的 JavaScript 将不会知道或被触发。因此您可能需要添加类似的内容

 onKeyUp='has_scrollbar("textareaID")'

Tommaso's solution works perfectly, even with a text area. But if the user were to type in the textarea and suddenly the textarea gave itself a scrollbar, your javascript wouldn't know or be triggered.So you might want to add something like

 onKeyUp='has_scrollbar("textareaID")'
長街聽風 2024-09-16 11:09:53

对于 React,我发现 https://github.com/andreypopp/react-textarea-autosize< /a>

import Textarea from 'react-textarea-autosize';
...

<Textarea maxRows={3} />

For React I've found https://github.com/andreypopp/react-textarea-autosize

import Textarea from 'react-textarea-autosize';
...

<Textarea maxRows={3} />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文