如何检查文本是否突出显示(跨浏览器) [英] How to check if text is highlighted (cross-browser)

查看:63
本文介绍了如何检查文本是否突出显示(跨浏览器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery或JavaScript(是否与大多数跨浏览器兼容)中是否有通用的方法来检查文本是否已突出显示?

Is there a generic way in jQuery or JavaScript (most cross-browser compatible) to check if text has been highlighted?

我正在使用HTML <input type='text'>元素.这是一个搜索框,允许在搜索项目时使用特定格式.

I am working with an HTML <input type='text'> element. This is a Search box that allows specific formats while searching for a Project.

用户可以输入以下内容:

A user can input the following:

  1. 项目名称,位置,描述和其他字母数字输入
  2. 项目编号(全数字)

keydown 上,我正在过滤各种搜索格式.按照目前的情况,如果输入了10个字符,并且全部都是数字字符,则input文本框将仅允许输入更多非数字字符.原因是我们的项目编号长10位,并且在用户搜索项目编号的情况下,我们只想捕获前10个字符,而忽略其余的字符.

On keydown I am filtering for various search formats. As it currently stands, if there are 10 characters entered, and they are all numeric, the input textbox will only allow for more characters to be entered if they are non-numeric. The reason for this is, our project numbers are 10 digits long, and in the case that a user is searching for a project number, we want to capture only the first 10 characters and ignore the rest.

我的目标是允许用户按项目编号查找项目,突出显示他们刚刚输入的文本,然后按项目编号搜索另一个项目(替换现有的搜索文本).但是,由于我们正在过滤非数字输入,因此不会捕获数字.

My goal is to allow for users to find a project by project number, highlight the text they just entered, and then search for another project by it's project number (replacing the existing search text). However, because we are filtering for non-numeric input, the numbers aren't captured.

这是我过滤非数字的方式:

Here is how I am filtering for non-numerics:

if ($input.val().length == 10 && !isNaN($input.val().replace(' ', '#'))) {
  if ((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105)) {
    return false;
  }
}

如何修改此内容以确保如果我的文本突出显示input将允许使用数字输入来替换现有查询?

How can I modify this to ensure that if my text is highlighted, the input will allow for numeric input to replace the existing query?

推荐答案

您可以使用Selection对象:

var selection = window.getSelection();

在此处查看文档: https://developer.mozilla. org/zh-CN/docs/Web/API/Selection

使用此对象,您可以检查选定的dom节点(anchorNode).例如:

With this object, you can check the selected dom node (anchorNode). For example :

if ($(window.getSelection().anchorNode).attr('id') === 'something') { ... }

这篇关于如何检查文本是否突出显示(跨浏览器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆