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

如何使用Userscript为HTML textarea元素添加line-height样式

错误原因

  • 你原有代码的核心问题是:document.querySelector("textarea") 返回的是DOM元素实例对象,不是HTML字符串,字符串方法replace不能直接作用在DOM对象上,自然无法生效。
  • 直接修改HTML字符串的方式非常不稳定,一旦原有style属性的值有任何变动(比如网站更新调整了内边距),匹配逻辑就会完全失效。

正确实现方案

方案1:直接操作DOM样式属性(最推荐)

直接通过元素的style接口修改行高,不会影响其他原有样式,也不需要匹配现有字符串:

(function() {
    'use strict';
    // 用更精准的属性选择器定位聊天输入框,避免匹配到页面其他textarea
    const chatTextarea = document.querySelector('textarea[data-test-selector="chat-input"]');
    if (chatTextarea) {
        chatTextarea.style.lineHeight = '1.0';
    }
})();

方案2:处理动态加载的元素

如果Userscript运行时输入框还没渲染到页面上,可以加轮询逻辑保证元素加载后再修改:

(function() {
    'use strict';
    const addLineHeight = () => {
        const chatTextarea = document.querySelector('textarea[data-test-selector="chat-input"]');
        if (chatTextarea) {
            chatTextarea.style.lineHeight = '1.0';
            // 找到元素后清除定时器
            clearInterval(timer);
        }
    };
    // 每300ms检查一次元素是否存在,最多检查20次(共6秒)可根据需求调整
    const timer = setInterval(addLineHeight, 300);
    addLineHeight();
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:27:01