You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Hyperscript中实现自动调整高度的textarea?

解决Hyperscript中textarea自动调整高度的问题

你遇到的核心问题是计算出的高度数值没有添加单位(比如px),浏览器无法识别无单位的长度值,所以设置高度的操作无效。

修正你的初始代码

只需要给计算结果拼接上px单位即可,两种写法都可行:

写法1:直接操作style属性

on keyup
    set calculatedHeight to Math.ceil((my value.length * 10) / my clientWidth) * 17
    log calculatedHeight
    set my.style.height to calculatedHeight & "px"

写法2:使用Hyperscript的属性语法(*height)

on keyup
    set calculatedHeight to Math.ceil((my value.length * 10) / my clientWidth) * 17
    log calculatedHeight
    set my *height to calculatedHeight & "px"

更准确的自动调整方案

你用字符长度和固定宽度计算的方式误差很大(比如不同字符宽度不同、换行符无法统计),更靠谱的方法是利用textarea的scrollHeight属性,它能准确获取内容的实际高度:

on keyup, input, change
    // 先重置高度为auto,让浏览器重新计算内容高度
    set my.style.height to "auto"
    // 设置高度为scrollHeight,确保内容完全显示
    set my.style.height to my.scrollHeight + "px"

这个方案还额外监听了input和change事件,覆盖粘贴文本、拖拽输入等场景,比只监听keyup更全面。

内容的提问来源于stack exchange,提问作者Nic Estrada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 16:28:21