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

如何让jQuery Terminal支持无文本区域的任意位置选中功能?

实现jQuery Terminal空白区域选中功能

要让jQuery Terminal支持传统终端(如Command Prompt、XTerm)的空白区域选中效果,核心思路是动态添加与终端行样式一致的伪空白行——这些行视觉透明但可被选中,从而填充终端可视区域的空白部分。以下是具体实现方案:

解决方案代码

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.terminal/js/jquery.terminal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery.terminal/css/jquery.terminal.min.css"/>
<style>
/* 伪空白行样式,完全匹配终端行的布局属性 */
.terminal-empty-line {
    height: var(--terminal-line-height);
    font-family: var(--terminal-font);
    font-size: var(--terminal-font-size);
    opacity: 0;
    user-select: text;
    pointer-events: none;
    white-space: pre;
}
</style>
</head>
<body>
<script>
const term = $('body').terminal({
    hello: function(what) {
        this.echo('Hello, ' + what + '. Welcome to this terminal.');
        // 输出内容后重新校准空白行数量
        fillEmptyLines();
    }
}, {
    greetings: 'My First Web Terminal',
    onInit: function() {
        fillEmptyLines();
        // 窗口大小变化时重新填充空白行
        $(window).on('resize', fillEmptyLines);
    }
});

function fillEmptyLines() {
    const terminal = term.get_container();
    // 从终端CSS变量获取行高,确保匹配终端布局
    const lineHeight = parseFloat(getComputedStyle(terminal).getPropertyValue('--terminal-line-height'));
    const terminalHeight = terminal.clientHeight;
    // 计算终端可视区域能容纳的总行数
    const totalLines = Math.floor(terminalHeight / lineHeight);
    // 统计已有内容行和空白行的总数
    const existingLines = terminal.querySelectorAll('.terminal-line, .terminal-empty-line').length;
    const emptyLinesNeeded = totalLines - existingLines;

    // 先清除旧的空白行,避免重复
    terminal.querySelectorAll('.terminal-empty-line').forEach(line => line.remove());

    // 添加新的空白行,用非断空格确保可选中
    for (let i = 0; i < emptyLinesNeeded; i++) {
        const emptyLine = document.createElement('div');
        emptyLine.className = 'terminal-empty-line';
        emptyLine.textContent = '\u00A0';
        terminal.appendChild(emptyLine);
    }
}
</script>
</body>
</html>

关键实现细节

  • 样式匹配:通过jQuery Terminal内置的CSS变量(--terminal-line-height、--terminal-font等)设置空白行样式,确保与真实终端行的高度、字体完全一致,选中范围精准。
  • 交互不冲突:pointer-events: none让空白行不干扰终端的点击、输入等原生交互。
  • 动态适配:在终端初始化、窗口resize、内容输出后,自动计算并填充足够的空白行,始终填满终端可视区域。
  • 可选中保障:空白行内添加\u00A0(非断空格),避免部分浏览器无法选中空元素的问题。

测试时拖动鼠标从终端内容区域到空白区域,即可实现类似传统终端的连续选中效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:02:45