如何获取文本区域内文本的高度

发布于 2024-09-11 09:08:00 字数 358 浏览 3 评论 0原文

我有一个带有文本 Hello Worldtextarea 。我想得到这段文字的高度。

我尝试使用:

var element = document.getElementById('textarea');
var textHeight = element.innerHTML.offsetHeight;

和:

var textHeight = element.value.offsetHeight;

但它们并没有给出文本的数字,而是给出了 textarea 元素的高度。

I have a textarea with the the text Hello World. I would like to get the height of this text.

I've tried to use:

var element = document.getElementById('textarea');
var textHeight = element.innerHTML.offsetHeight;

and:

var textHeight = element.value.offsetHeight;

But these don't give the numbers of the text, but the height of the textarea element.

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

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

发布评论

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

评论(8

她如夕阳 2024-09-18 09:08:00

element.scrollHeight 可能值得研究。

如果我要解决这个问题(我根本没有测试过这个),我会将文本区域的高度设置为 1px 测量滚动高度,然后重置文本区域的高度。

https://developer.mozilla.org/en-US/docs /Web/API/Element/scrollHeight

element.scrollHeight is probably worth investigating.

If I was going to approach this (and I've not tested this at all), I'd set the textarea's height to 1px measure the scroll height and then reset the textarea's height.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

凉宸 2024-09-18 09:08:00

创建一个span元素,将Span的innerHTML设置为“Hello World”。
获取跨度的 offsetHeight。

var span = document.createElement("span");
span.innerHTML="Hello World"; //or whatever string you want.
span.offsetHeight // this is the answer

请注意,您必须将跨度的字体样式设置为文本区域的字体样式。

你的例子永远不会工作,因为innerHTML和value都是字符串。 String 没有定义 offsetWidth。

如果您希望获取文本区域内选定文本的高度,请使用 SelectionStart/selectionEnd 查找文本区域的选定文本。

Create a span element, set Span's innerHTML to "Hello World".
Get the span's offsetHeight.

var span = document.createElement("span");
span.innerHTML="Hello World"; //or whatever string you want.
span.offsetHeight // this is the answer

note that you must set the span's font style to the textarea's font style.

Your example will NEVER work because innerHTML and value are both strings. String doesn't define offsetWidth.

If you wish to get the height of selected text inside of a textarea, use selectionStart/selectionEnd to find the selected text of the textarea.

极度宠爱 2024-09-18 09:08:00

jQuery 中没有scrollHeight,因此需要一些解决方法。解决方案将是:

var areaheight=$("textarea#element")[0].scrollHeight;
$("#element").height(areaheight);

或更短:

$("#element").height($("#element")[0].scrollHeight)

In jQuery there is no scrollHeight, so it needs a little workaround. the solution would be:

var areaheight=$("textarea#element")[0].scrollHeight;
$("#element").height(areaheight);

or shorter:

$("#element").height($("#element")[0].scrollHeight)
嘿嘿嘿 2024-09-18 09:08:00

您可以使用 element.scrollHeight (就像帕特里克回答的那样),但它需要一些更正(我在示例中使用 jQuery):

1)如果您的文本区域有填充,您需要减去它(顶部和底部)。

2)如果元素已经设置了高度,则需要将其设置为零(仅用于测量然后将其设置回来,否则返回此高度+填充)

var h0 = $(element).height();  // backup height
$(this).height(0); 
var h = $(this).get(0).scrollHeight - $(this).css('paddingTop').replace('px','')*1 - $(this).css('paddingBottom').replace('px','')*1; // actual text height
$(this).height(h0); // set back original height (or new height using h)

不需要与textarea具有相同css的额外跨度。

You can use element.scrollHeight (just like Patrick answered) but it needs some corrections (I'm using jQuery in example):

1) if your textarea has padding, you need to substract it (top & bottom).

2) if element has already set height, you need to set it to zero (just for measure then set it back, else it returns this height + padding)

var h0 = $(element).height();  // backup height
$(this).height(0); 
var h = $(this).get(0).scrollHeight - $(this).css('paddingTop').replace('px','')*1 - $(this).css('paddingBottom').replace('px','')*1; // actual text height
$(this).height(h0); // set back original height (or new height using h)

There is no need of extra span with same css as textarea.

So要识趣 2024-09-18 09:08:00

对于任何使用 React 的人:

const textarea_ref = useRef(null);
const [idealHeight,setIdealHeight] = useState(0);
const [inputValue,setInputValue] = useState("");


useLayoutEffect(() => {                                           // useLayoutEffect TO AVOID FLICKERING
    textarea_ref.current.style.height = '0px';                    // NEEDS TO SET HEIGHT TO ZERO
    const scrollHeight = textarea_ref.current.scrollHeight;       // TO READ THE CORRECT SCROLL HEIGHT WHEN IT SHRINKS
    textarea_ref.current.removeAttribute('style');                // REMOVE INLINE STYLE THAT WAS ADDED WITH 0px
    setIdealHeight(scrollHeight + 2);                             // NEEDS TO ADD 2. I THINK IT'S BECAUSE OF THE BORDER
  },[inputValue]);

return (
  <textarea
    // USE idealHeight STATE TO SET THE HEIGHT
    value={inputValue}
    onChange={onChange}
    ref={textarea_ref}
  />
);

PS:它有时仍然会闪烁。至少在 Chrome 中是这样。

For anyone using React:

const textarea_ref = useRef(null);
const [idealHeight,setIdealHeight] = useState(0);
const [inputValue,setInputValue] = useState("");


useLayoutEffect(() => {                                           // useLayoutEffect TO AVOID FLICKERING
    textarea_ref.current.style.height = '0px';                    // NEEDS TO SET HEIGHT TO ZERO
    const scrollHeight = textarea_ref.current.scrollHeight;       // TO READ THE CORRECT SCROLL HEIGHT WHEN IT SHRINKS
    textarea_ref.current.removeAttribute('style');                // REMOVE INLINE STYLE THAT WAS ADDED WITH 0px
    setIdealHeight(scrollHeight + 2);                             // NEEDS TO ADD 2. I THINK IT'S BECAUSE OF THE BORDER
  },[inputValue]);

return (
  <textarea
    // USE idealHeight STATE TO SET THE HEIGHT
    value={inputValue}
    onChange={onChange}
    ref={textarea_ref}
  />
);

PS: It still flickers sometimes. At least in Chrome.

倒数 2024-09-18 09:08:00

可以通过获取textarea滚动条高度来获取文本高度

const textarea = document.getElementByTagName("textarea");
const height = textarea.scrollHeight;

console.log({ height });

You can get the text height by getting the textarea scrollbar height

const textarea = document.getElementByTagName("textarea");
const height = textarea.scrollHeight;

console.log({ height });
萌︼了一个春 2024-09-18 09:08:00

http://www.quirksmode.org/dom/range_intro.html
抱歉,我无法提供更多帮助。

你的例子的问题是内联文本没有高度,它只有一个行高,为了让它有一个高度,它需要处于显示块模式,以便所有行都添加到文本块中,即便如此,这一切都取决于框的宽度以及字体大小、字体系列等。

ItzWarty 建议获取文本选择并将其放入与文本区域具有相同字体和宽度的 div 中,其中有显示块并允许您获取其高度。

http://www.quirksmode.org/dom/range_intro.html
sorry that I can't be of more help.

the problem with you example is that inline text does not have a height, it only has a line-height, for it to have a height it needs to be in display block mode, so that all the lines are added to a block of text, even then it all depends on the width of the box and the font-size, font-family etc.

what ItzWarty suggests is getting the text selection and putting it in a div that has the same font and width as the textarea, which has display block and allows you to get its height.

大姐,你呐 2024-09-18 09:08:00

我不确定我是否正确解释了您的问题,但我个人需要知道每行文本的确切高度line-height 属性没有正确的值(例如,在 Safari 中,实际打印文本时它将四舍五入到最接近的值)。

这是我的解决方法。您应该在文档开头的某个位置包含以下代码。

// set one row in the textarea and get its height
element.rows = 1;
var height1 = parseFloat(window.getComputedStyle(element)["height"]);
// set two rows in the textarea and get its height
element.rows = 2;
var height2 = parseFloat(window.getComputedStyle(element)["height"]);
// Now, the line height should be the difference
var inputLineHeight = height2-height1;

变量 inputLineHeight 应包含正确的值(以像素为单位)。

I am not sure whether I interpret your question correctly, but I personally needed to know the exact height of each line of text. The line-height property does not have the right value (for example, in Safari, it will be rounded to the closest value when actually printing text).

This is my workaround. You should have the following code somewhere at the beginning of the document.

// set one row in the textarea and get its height
element.rows = 1;
var height1 = parseFloat(window.getComputedStyle(element)["height"]);
// set two rows in the textarea and get its height
element.rows = 2;
var height2 = parseFloat(window.getComputedStyle(element)["height"]);
// Now, the line height should be the difference
var inputLineHeight = height2-height1;

The variable inputLineHeight should contain the correct value, in pixel.

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