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

同一页面双ACE Editor窗口:其一自动调正常另一失效求助

排查ACE Editor窗口2无法自动调整尺寸的问题

嘿,我之前也踩过ACE Editor尺寸适配的坑,咱们一步步来找出窗口2的问题所在!

最常见的几个原因&解决方案

1. 变量实例引用错误

你给的代码片段里是window1.getSession(),窗口2的高度更新函数里是不是复制后没把变量名改成window2?这是最容易犯的低级错误!如果窗口2的函数里还是用window1,那它只会更新第一个编辑器的高度,窗口2自然没反应。

2. 事件绑定缺失

窗口1应该是绑定了change事件来触发高度更新,窗口2是不是漏了这一步?ACE Editor不会自动监听内容变化,必须手动绑定事件触发高度计算函数。

3. 容器CSS限制

检查窗口2的父容器或者编辑器本身的CSS:有没有设置fixed height、max-height、overflow: hidden?这些样式会限制编辑器的高度,就算计算出正确的高度也没法撑开。

4. 初始化顺序问题

如果窗口2是动态创建的(比如通过JS添加到DOM),是不是在编辑器实例还没初始化完成就调用了高度更新函数?或者加载远程内容时,没在内容加载完成后触发高度计算?

修正后的完整示例代码

$(document).ready(function() {
    // 窗口1(正常工作的配置)
    const window1 = ace.edit("editor1");
    const updateHeightWindow1 = () => {
        const lineCount = window1.getSession().getScreenLength();
        const lineHeight = window1.renderer.lineHeight;
        const scrollBarWidth = window1.renderer.scrollBar.getWidth();
        const newHeight = lineCount * lineHeight + scrollBarWidth;
        $("#editor1").height(`${newHeight}px`);
        window1.resize(); // 通知编辑器重新渲染
    };
    // 绑定内容变化事件
    window1.on("change", updateHeightWindow1);
    // 初始化时先执行一次,适配初始内容
    updateHeightWindow1();

    // 窗口2(修正后的配置)
    const window2 = ace.edit("editor2"); // 确保DOM选择器#editor2存在
    const updateHeightWindow2 = () => {
        // 这里必须用window2的实例!
        const lineCount = window2.getSession().getScreenLength();
        const lineHeight = window2.renderer.lineHeight;
        const scrollBarWidth = window2.renderer.scrollBar.getWidth();
        const newHeight = lineCount * lineHeight + scrollBarWidth;
        $("#editor2").height(`${newHeight}px`);
        window2.resize();
    };
    // 千万别忘了绑定事件!
    window2.on("change", updateHeightWindow2);
    // 初始化执行+如果是加载远程内容,要在内容加载完后调用这个函数
    updateHeightWindow2();
});

额外排查步骤

  • 打开浏览器控制台看报错:如果有window2 is not defined或者Cannot read property 'getSession' of undefined这类错误,直接定位问题根源。
  • 测试初始内容:如果窗口2初始是空的,可以手动输入几行文字,看高度会不会变化;如果是加载外部代码,要在代码加载完成的回调里调用updateHeightWindow2()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:17:49