javascript - 如何让 window.getselection 为输入类型=文本字段工作

标签 javascript html contenteditable caret

我有一个 contenteditable div,像这样:

<div id="test" contentEditable="true" style="width: 600px; height:300px;">Lorem ipsum dolor sit amet</div>

为此我使用以下代码:

<input type="button" value="Click me" onclick="alert(window.getSelection().focusOffset.toString());"></button>

当我在 div 中四处移动插入符号时单击按钮,返回插入符号在 div 中的实际位置(偏移量)。

问题是,当我将 contenteditable div 替换为输入类型 = 文本或密码控件,并保持 contenteditable 属性 = true,然后单击按钮时,我总是得到零。这是为什么?

感谢您的关注。

最佳答案

在大多数浏览器中,window.getSelection()仅适用于文本节点内的选择和文档内的元素。它不适用于 <input> 内的文本和 <textarea>元素(尽管在 WebKit 中 window.getSelection().toString() 将在聚焦文本输入或文本区域内返回选定的文本。参见 http://jsfiddle.net/PUdaS/ )。要在输入中获取选择,请使用输入的 selectionStart and selectionEnd 属性:

<input type="text" id="test" value="Some text">

<input type="button" value="Click me"
    onclick="alert(document.getElementById('test').selectionEnd);">

请注意,IE 8 及更高版本不支持 selectionStartselectionEnd属性,和一个 different, more complicated solution是必须的。 IE 不支持 window.getSelection()要么,因此此代码将适用于您的原始代码所支持的所有浏览器。

关于javascript - 如何让 window.getselection 为输入类型=文本字段工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5072155/

相关文章:

javascript - 在 Javascript 中通过引用访问变量

javascript - ECMAScript 5 - 错误缺少类属性转换

javascript - SVG 到 PDF 的转换适用于 Plotly.js 但不适用于 C3.js

javascript - 使用 Canvas 作为多个范围输入的垫

javascript - 在内容可编辑的段落中存在的粗体元素内设置插入符号(光标)

javascript - 如何在 Pusher 中创建用户特定 channel ?

html - Bootstrap 4 网格布局不适用于 dompdf

php - 表单发送空白值

css - 内联 contenteditable 标签无法在 IE 中正确对齐

javascript - 如何初始化和自定义contenteditable div中的节点结构