Javascript detect scrollbar in textarea

狂风中的少年 提交于 2019-11-26 20:37:35

问题


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.


回答1:


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/




回答2:


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")'



回答3:


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');



回答4:


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

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

<Textarea maxRows={3} />


来源:https://stackoverflow.com/questions/3238515/javascript-detect-scrollbar-in-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!