Skip to content

WORD相关事件

选择变化事件

OnWordWPSSelChange

语法

javascript
OnWordWPSSelChange(Selection)

参数

名称必选/可选数据类型说明
Selection必选object返回代码改变的插入点对象

说明

当Word或者WPS文档的插入点或者选中内容改变时触发此事件。

示例代码

javascript
// Word选择变化事件处理
function OnWordWPSSelChange(Selection) {
    console.log("Word选择变化事件触发");
    console.log("选择对象:", Selection);
    
    // 获取选择范围信息
    var selectionInfo = getSelectionInfo(Selection);
    console.log("选择信息:", selectionInfo);
    
    // 处理选择变化
    handleSelectionChange(selectionInfo);
}

// 获取选择信息
function getSelectionInfo(selection) {
    try {
        var info = {
            text: selection.Text,
            start: selection.Start,
            end: selection.End,
            length: selection.End - selection.Start
        };
        return info;
    } catch (error) {
        console.error("获取选择信息失败:", error);
        return null;
    }
}

// 处理选择变化
function handleSelectionChange(selectionInfo) {
    if (selectionInfo && selectionInfo.length > 0) {
        console.log("选中文本:", selectionInfo.text);
        console.log("选择长度:", selectionInfo.length);
        
        // 显示选择信息
        showSelectionInfo(selectionInfo);
        
        // 更新工具栏状态
        updateToolbarState(selectionInfo);
    } else {
        console.log("无选中内容");
        // 隐藏选择相关工具栏
        hideSelectionToolbar();
    }
}

// 显示选择信息
function showSelectionInfo(selectionInfo) {
    // 在状态栏显示选择信息
    var statusText = "选中 " + selectionInfo.length + " 个字符";
    updateStatusBar(statusText);
}

// 更新工具栏状态
function updateToolbarState(selectionInfo) {
    // 启用复制、剪切等按钮
    enableCopyButtons();
    
    // 根据选择内容启用相应功能
    if (isTextSelected(selectionInfo.text)) {
        enableTextFormatting();
    }
    
    if (isTableSelected(selectionInfo.text)) {
        enableTableEditing();
    }
}

// 检查是否选中文本
function isTextSelected(text) {
    return text && text.trim().length > 0;
}

// 检查是否选中表格
function isTableSelected(text) {
    return text && text.includes('\t');
}

右键事件

OnWordBeforeRightClick

语法

javascript
OnWordBeforeRightClick(Selection, IsCancel)

参数

名称必选/可选数据类型说明
Selection必选object返回代码改变的插入点对象
IsCancel必选bool是否取消事件

说明

该事件在WORD、WPS右键事件发生之前激活。 第一个参数是Selection指明了事件发生的Selection对象,第2个参数是是否取消事件。可设置为true来取消事件。

示例代码

html
<object name='webwps' id='webwps_id' type='application/ntko-plug' 
        data='/opt/kingsoft/wps-office/office6/mui/default/templates/Normal.dotm' 
        width='1000' height='600' _FileNew=false  
        ForOnWordBeforeRightClick="OnWordBeforeRightClick">
</object>
javascript
// Word右键事件处理
function OnWordBeforeRightClick(Selection, IsCancel) {
    console.log("Word右键事件触发");
    console.log("选择对象:", Selection);
    
    // 获取右键位置信息
    var rightClickInfo = getRightClickInfo(Selection);
    console.log("右键信息:", rightClickInfo);
    
    // 检查是否应该显示自定义右键菜单
    if (shouldShowCustomContextMenu(rightClickInfo)) {
        // 取消默认右键菜单
        IsCancel.SetValue(true);
        
        // 显示自定义右键菜单
        showCustomContextMenu(rightClickInfo);
    } else {
        // 允许默认右键菜单
        IsCancel.SetValue(false);
    }
}

// 获取右键位置信息
function getRightClickInfo(selection) {
    try {
        var info = {
            text: selection.Text,
            start: selection.Start,
            end: selection.End,
            position: selection.Range.Start
        };
        return info;
    } catch (error) {
        console.error("获取右键信息失败:", error);
        return null;
    }
}

// 检查是否应该显示自定义右键菜单
function shouldShowCustomContextMenu(rightClickInfo) {
    if (!rightClickInfo) return false;
    
    // 根据选择内容决定是否显示自定义菜单
    if (rightClickInfo.text && rightClickInfo.text.trim().length > 0) {
        return true; // 有选中文本时显示自定义菜单
    }
    
    // 根据位置决定
    if (isInSpecialArea(rightClickInfo.position)) {
        return true; // 在特殊区域时显示自定义菜单
    }
    
    return false;
}

// 检查是否在特殊区域
function isInSpecialArea(position) {
    // 检查是否在表格、图片等特殊区域
    // 这里可以根据具体需求实现
    return false;
}

// 显示自定义右键菜单
function showCustomContextMenu(rightClickInfo) {
    console.log("显示自定义右键菜单");
    
    // 创建自定义右键菜单
    var contextMenu = createContextMenu(rightClickInfo);
    
    // 显示菜单
    showContextMenu(contextMenu);
}

// 创建自定义右键菜单
function createContextMenu(rightClickInfo) {
    var menuItems = [];
    
    if (rightClickInfo.text && rightClickInfo.text.trim().length > 0) {
        // 有选中文本时的菜单项
        menuItems.push({
            text: "复制",
            action: function() { copySelectedText(); }
        });
        menuItems.push({
            text: "剪切",
            action: function() { cutSelectedText(); }
        });
        menuItems.push({
            text: "粘贴",
            action: function() { pasteText(); }
        });
        menuItems.push({
            text: "删除",
            action: function() { deleteSelectedText(); }
        });
    } else {
        // 无选中文本时的菜单项
        menuItems.push({
            text: "粘贴",
            action: function() { pasteText(); }
        });
        menuItems.push({
            text: "插入表格",
            action: function() { insertTable(); }
        });
        menuItems.push({
            text: "插入图片",
            action: function() { insertImage(); }
        });
    }
    
    return menuItems;
}

// 显示右键菜单
function showContextMenu(menuItems) {
    // 创建菜单元素
    var menu = document.createElement('div');
    menu.className = 'custom-context-menu';
    
    // 添加菜单项
    menuItems.forEach(function(item) {
        var menuItem = document.createElement('div');
        menuItem.className = 'context-menu-item';
        menuItem.textContent = item.text;
        menuItem.onclick = item.action;
        menu.appendChild(menuItem);
    });
    
    // 添加到页面
    document.body.appendChild(menu);
    
    // 设置菜单位置
    positionContextMenu(menu);
    
    // 点击其他地方隐藏菜单
    document.addEventListener('click', function() {
        document.body.removeChild(menu);
    });
}

// 设置菜单位置
function positionContextMenu(menu) {
    // 获取鼠标位置
    var mouseX = event.clientX;
    var mouseY = event.clientY;
    
    // 设置菜单位置
    menu.style.position = 'absolute';
    menu.style.left = mouseX + 'px';
    menu.style.top = mouseY + 'px';
    menu.style.zIndex = '9999';
}

// 复制选中文本
function copySelectedText() {
    console.log("复制选中文本");
    // 执行复制操作
}

// 剪切选中文本
function cutSelectedText() {
    console.log("剪切选中文本");
    // 执行剪切操作
}

// 粘贴文本
function pasteText() {
    console.log("粘贴文本");
    // 执行粘贴操作
}

// 删除选中文本
function deleteSelectedText() {
    console.log("删除选中文本");
    // 执行删除操作
}

// 插入表格
function insertTable() {
    console.log("插入表格");
    // 执行插入表格操作
}

// 插入图片
function insertImage() {
    console.log("插入图片");
    // 执行插入图片操作
}

完整示例

Word事件管理器

javascript
// Word事件管理器
class WordEventManager {
    constructor() {
        this.selectionHistory = [];
        this.contextMenuHandlers = new Map();
        this.selectionChangeHandlers = [];
    }
    
    // 注册选择变化处理器
    registerSelectionChangeHandler(handler) {
        this.selectionChangeHandlers.push(handler);
    }
    
    // 注册右键菜单处理器
    registerContextMenuHandler(condition, handler) {
        this.contextMenuHandlers.set(condition, handler);
    }
    
    // 处理选择变化
    handleSelectionChange(selection) {
        console.log("处理选择变化");
        
        // 记录选择历史
        this.recordSelectionHistory(selection);
        
        // 通知所有处理器
        this.selectionChangeHandlers.forEach(handler => {
            try {
                handler(selection);
            } catch (error) {
                console.error("选择变化处理器错误:", error);
            }
        });
    }
    
    // 处理右键事件
    handleRightClick(selection, isCancel) {
        console.log("处理右键事件");
        
        // 检查是否需要自定义右键菜单
        var shouldShowCustom = this.shouldShowCustomContextMenu(selection);
        
        if (shouldShowCustom) {
            isCancel.SetValue(true);
            this.showCustomContextMenu(selection);
        } else {
            isCancel.SetValue(false);
        }
    }
    
    // 记录选择历史
    recordSelectionHistory(selection) {
        try {
            var selectionInfo = {
                text: selection.Text,
                start: selection.Start,
                end: selection.End,
                timestamp: new Date().toISOString()
            };
            
            this.selectionHistory.push(selectionInfo);
            
            // 限制历史记录数量
            if (this.selectionHistory.length > 100) {
                this.selectionHistory.shift();
            }
        } catch (error) {
            console.error("记录选择历史失败:", error);
        }
    }
    
    // 检查是否应该显示自定义右键菜单
    shouldShowCustomContextMenu(selection) {
        for (var [condition, handler] of this.contextMenuHandlers) {
            if (condition(selection)) {
                return true;
            }
        }
        return false;
    }
    
    // 显示自定义右键菜单
    showCustomContextMenu(selection) {
        console.log("显示自定义右键菜单");
        // 实现自定义右键菜单逻辑
    }
}

// 创建Word事件管理器实例
const wordEventManager = new WordEventManager();

// 注册选择变化处理器
wordEventManager.registerSelectionChangeHandler(function(selection) {
    console.log("选择变化:", selection.Text);
});

// 注册右键菜单处理器
wordEventManager.registerContextMenuHandler(
    function(selection) {
        return selection.Text && selection.Text.trim().length > 0;
    },
    function(selection) {
        console.log("显示文本右键菜单");
    }
);

// 全局事件处理函数
function OnWordWPSSelChange(Selection) {
    wordEventManager.handleSelectionChange(Selection);
}

function OnWordBeforeRightClick(Selection, IsCancel) {
    wordEventManager.handleRightClick(Selection, IsCancel);
}

Word功能增强

javascript
// Word功能增强
class WordFeatureEnhancer {
    constructor() {
        this.features = new Map();
        this.initFeatures();
    }
    
    // 初始化功能
    initFeatures() {
        this.features.set('smartSelection', true);
        this.features.set('contextMenu', true);
        this.features.set('autoSave', true);
        this.features.set('spellCheck', true);
    }
    
    // 智能选择功能
    enableSmartSelection() {
        this.features.set('smartSelection', true);
        console.log("智能选择功能已启用");
    }
    
    // 上下文菜单功能
    enableContextMenu() {
        this.features.set('contextMenu', true);
        console.log("上下文菜单功能已启用");
    }
    
    // 自动保存功能
    enableAutoSave() {
        this.features.set('autoSave', true);
        console.log("自动保存功能已启用");
    }
    
    // 拼写检查功能
    enableSpellCheck() {
        this.features.set('spellCheck', true);
        console.log("拼写检查功能已启用");
    }
    
    // 检查功能是否启用
    isFeatureEnabled(featureName) {
        return this.features.get(featureName) || false;
    }
    
    // 处理选择变化
    handleSelectionChange(selection) {
        if (this.isFeatureEnabled('smartSelection')) {
            this.processSmartSelection(selection);
        }
        
        if (this.isFeatureEnabled('spellCheck')) {
            this.processSpellCheck(selection);
        }
    }
    
    // 处理智能选择
    processSmartSelection(selection) {
        console.log("处理智能选择");
        // 实现智能选择逻辑
    }
    
    // 处理拼写检查
    processSpellCheck(selection) {
        console.log("处理拼写检查");
        // 实现拼写检查逻辑
    }
}

// 创建功能增强器实例
const wordFeatureEnhancer = new WordFeatureEnhancer();

// 启用所有功能
wordFeatureEnhancer.enableSmartSelection();
wordFeatureEnhancer.enableContextMenu();
wordFeatureEnhancer.enableAutoSave();
wordFeatureEnhancer.enableSpellCheck();

注意事项

  1. 事件绑定

    • 确保在HTML中正确绑定事件处理函数
    • 事件函数名要与HTML中的属性值一致
    • 注意大小写和拼写
  2. 参数处理

    • 检查参数的有效性
    • 处理可选参数的情况
    • 注意参数的数据类型
  3. 选择对象

    • 安全地访问Selection对象属性
    • 处理访问失败的情况
    • 注意对象生命周期
  4. 右键菜单

    • 合理控制自定义右键菜单的显示
    • 处理菜单项点击事件
    • 注意菜单的定位和样式
  5. 性能优化

    • 避免在事件处理中执行耗时操作
    • 合理使用异步操作
    • 避免重复处理
  6. 错误处理

    • 处理事件处理中的异常
    • 提供用户友好的错误信息
    • 记录错误日志
  7. 用户体验

    • 提供及时的状态反馈
    • 显示操作进度
    • 处理用户交互
  8. 兼容性

    • 考虑不同浏览器的兼容性
    • 处理不同版本的差异
    • 测试各种场景