如何实现TinyMCE工具栏在元素滚动(非窗口滚动)时固定?
问题描述
我们在实现TinyMCE工具栏的固定(sticky)效果时遇到问题:在常规窗口滚动的测试应用中功能正常,但在自身应用里无法生效——我们的应用没有窗口级滚动,仅使用div/元素滚动。
使用的TinyMCE版本为5.9.0,初始化配置如下:
tinyConfig: { selector: '#' + elementId, suffix: '.min', base_url: '/app/tinymce', skin_url: '/app/tinymce/skins/ui/oxide', content_css: '/app/tinymce/skins/ui/oxide/content.min.css', theme: 'silver', browser_spellcheck: true, contextmenu: false, toolbar_sticky: true, toolbar_sticky_offset: 150 } // 初始化 tinymce.init(this.tinyConfig);
对应的HTML结构:
<body style="height: 100%; width: 100%; margin: 0;padding: 0; overflow: hidden; scroll-behavior: smooth;"> <main class = "d-inline-block w-100 overflow-hidden position-relative"> <section class="pl-default pr-default pb-default overflow-y-auto" style="overflow-x: hidden;"> <rich-text-editor> </rich-text-editor> </section> </main> </body>
我们曾尝试给滚动元素添加事件监听器并触发TinyMCE的ScrollWindow事件,虽然能让工具栏固定,但无法取消固定,且尺寸调整等其他事件也无法正常工作,尝试的代码如下:
document.getElementById('sectionId').addEventListner(); // 存在拼写错误:addEventListner → addEventListener document.addEventListener('scroll', event => { this._tinyMceInstance.fire('ScrollWindow', event); });
解决方法
TinyMCE默认监听window对象的滚动事件,当滚动容器为自定义元素时,需要手动调整事件监听逻辑,确保工具栏能正确切换固定/非固定状态:
修正滚动事件监听目标
直接监听带滚动的section元素,而非全局document,同时修正代码拼写错误:const scrollContainer = document.getElementById('sectionId'); scrollContainer.addEventListener('scroll', handleContainerScroll);传递正确的滚动参数触发编辑器事件
直接触发ScrollWindow时,需手动计算滚动容器的偏移量,确保编辑器能正确判断工具栏状态,同时触发ResizeWindow保证位置计算准确:function handleContainerScroll() { const scrollTop = scrollContainer.scrollTop; // 传递自定义滚动参数给编辑器 this._tinyMceInstance.fire('ScrollWindow', { target: scrollContainer, currentTarget: scrollContainer, scrollTop: scrollTop }); // 触发resize事件同步工具栏位置 this._tinyMceInstance.fire('ResizeWindow'); }指定编辑器的滚动容器(可选)
若你的TinyMCE 5.9.0版本支持scroll_container配置项,可在初始化时直接绑定滚动容器,减少手动事件监听的代码:tinyConfig: { // 原有配置... toolbar_sticky: true, toolbar_sticky_offset: 150, scroll_container: '#sectionId' // 绑定自定义滚动容器选择器 }确保滚动容器样式合规
滚动容器需明确设置高度(或通过父级布局限制高度),保证overflow-y-auto生效;同时避免容器的position属性干扰工具栏的固定定位逻辑。
内容的提问来源于stack exchange,提问作者isUserAkanksha
相关产品推荐
相关产品推荐

