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

JavaScript/jQuery中是否存在用户停止选中输入框/文本域文本的事件?

实现文本取消选中时清空变量的方案

好问题!其实jQuery本身并没有专门的「停止选中文本」事件,但我们可以通过组合几个常见的事件来完美实现你想要的效果。

先回顾一下你的现有代码:

var lastTextSelected = ""; //两个元素均为textarea
jQuery('#ingredients').select(selectedText);
jQuery('#steps').select(selectedText);

function selectedText() {
  lastTextSelected = window.getSelection().toString();
}

当前代码只会在用户选中文本时触发select事件并记录内容,但没有处理取消选中的场景——比如用户点击页面其他区域、点击textarea内的空白处、按下Esc键取消选中,或者切换到其他输入框时,都需要清空lastTextSelected。

具体实现方案

我们可以通过监听以下几个事件来覆盖绝大多数取消选中的场景:

  1. 监听元素失去焦点(blur事件)
    当用户点击textarea以外的区域,元素失去焦点时,直接清空变量:
jQuery('#ingredients, #steps').on('blur', function() {
  lastTextSelected = "";
});
  1. 监听鼠标松开(mouseup事件)
    当用户松开鼠标时(不管是在textarea内还是页面其他地方),检查当前是否还有选中的文本,如果没有就清空变量:
jQuery(document).on('mouseup', function() {
  var currentSelection = window.getSelection().toString();
  if (!currentSelection) {
    lastTextSelected = "";
  }
});
  1. 监听键盘按键(keyup事件)
    处理用键盘操作取消选中的场景(比如按下Esc键,或者用Shift+箭头选中后再取消):
jQuery(document).on('keyup', function(e) {
  // 按下Esc键 或者 当前无选中文本时清空变量
  if (e.key === 'Escape' || !window.getSelection().toString()) {
    lastTextSelected = "";
  }
});

整合后的完整代码

把这些事件和你原有的代码整合后,最终代码如下:

var lastTextSelected = "";

// 原有的文本选中事件
function selectedText() {
  lastTextSelected = window.getSelection().toString();
}
jQuery('#ingredients, #steps').select(selectedText);

// 元素失去焦点时清空
jQuery('#ingredients, #steps').on('blur', function() {
  lastTextSelected = "";
});

// 鼠标松开时检查并清空
jQuery(document).on('mouseup', function() {
  var currentSelection = window.getSelection().toString();
  if (!currentSelection) {
    lastTextSelected = "";
  }
});

// 键盘操作取消选中时清空
jQuery(document).on('keyup', function(e) {
  if (e.key === 'Escape' || !window.getSelection().toString()) {
    lastTextSelected = "";
  }
});

这样就能在用户停止选中文本的各种场景下,自动清空lastTextSelected变量啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:02:20