如何制作可鼠标调整大小的Google Sheets插件浮动控制面板?
实现Google Sheets插件可调整大小的浮动面板
Google Sheets原生侧边栏宽度固定,模态/非模态对话框仅支持拖动标题栏调整位置,要实现类似Formula Studio的可调整大小浮动面板,需通过前端自定义拖拽逻辑结合Apps Script对话框API实现,具体步骤如下:
1. 后端Apps Script代码
创建打开非模态对话框的函数,设置初始宽高:
function openResizableDialog() { const htmlOutput = HtmlService.createHtmlOutputFromFile('ResizableDialog') .setWidth(400) // 初始宽度 .setHeight(300); // 初始高度 SpreadsheetApp.getUi().showModelessDialog(htmlOutput, '可调整大小面板'); }
2. 前端HTML页面(ResizableDialog.html)
在HTML中添加拖拽手柄,通过JavaScript监听鼠标事件实现尺寸调整:
<!DOCTYPE html> <html> <head> <base target="_top"> <style> /* 面板容器样式 */ .dialog-container { position: relative; width: 100%; height: 100%; padding: 12px; box-sizing: border-box; } /* 右下角拖拽手柄 */ .resize-handle { position: absolute; right: 0; bottom: 0; width: 18px; height: 18px; background-color: #e0e0e0; cursor: nwse-resize; border-top-left-radius: 4px; border: 1px solid #ccc; } /* 内容区域,留出手柄空间 */ .content-area { height: calc(100% - 25px); overflow-y: auto; } </style> </head> <body> <div class="dialog-container"> <div class="content-area"> <!-- 这里放置你的插件功能内容 --> <h3>自定义面板内容</h3> <p>拖动右下角手柄即可调整面板大小</p> </div> <div class="resize-handle" id="resizeHandle"></div> </div> <script> const resizeHandle = document.getElementById('resizeHandle'); let isResizing = false; let startX, startY, initialWidth, initialHeight; // 监听手柄按下事件 resizeHandle.addEventListener('mousedown', initResize); function initResize(e) { isResizing = true; // 记录初始鼠标位置和面板当前尺寸 startX = e.clientX; startY = e.clientY; const dialogWrapper = document.querySelector('body').parentElement; initialWidth = parseInt(dialogWrapper.style.width || dialogWrapper.offsetWidth); initialHeight = parseInt(dialogWrapper.style.height || dialogWrapper.offsetHeight); // 添加全局鼠标移动/抬起监听 document.addEventListener('mousemove', handleResize); document.addEventListener('mouseup', stopResize); e.preventDefault(); // 避免触发文本选择等默认行为 } // 实时调整面板尺寸 function handleResize(e) { if (!isResizing) return; const dialogWrapper = document.querySelector('body').parentElement; // 计算新尺寸 const newWidth = initialWidth + (e.clientX - startX); const newHeight = initialHeight + (e.clientY - startY); // 设置最小尺寸限制(可自定义) if (newWidth >= 300 && newHeight >= 200) { dialogWrapper.style.width = `${newWidth}px`; dialogWrapper.style.height = `${newHeight}px`; } } // 停止调整 function stopResize() { isResizing = false; document.removeEventListener('mousemove', handleResize); document.removeEventListener('mouseup', stopResize); } </script> </body> </html>
关键说明
- 核心逻辑:前端JS直接修改Google对话框外层容器的
width和height样式,原生API不支持调整大小,需自定义实现。 - 非模态对话框:使用
showModelessDialog而非模态对话框,允许用户同时操作表格和面板,提升体验。 - 尺寸限制:代码中设置了最小宽高(300px/200px),可根据需求修改,避免面板被拖得过小。
- 扩展优化:若需记住用户调整后的尺寸,可通过
PropertiesService.getUserProperties()存储宽高值,下次打开对话框时自动加载。
内容的提问来源于stack exchange,提问作者SoftTimur
相关产品推荐
相关产品推荐

