对编程创建的输入使用selectionStart

using selectionStart on programmatically-created inputs

本文关键字:selectionStart 输入 编程 创建      更新时间:2023-09-26

是否可以在我以编程方式创建的<textarea>上设置和获取.selectionStart.selectionEnd ?

var input = document.createElement("textarea");
input.selectionStart; // 0 - just to confirm the property exists
input.selectionStart = 2; // returns 2
input.selectionStart; // returns 0, it should be 2

上面的工作很好,在textarea实际上存在于页面的HTML中,但不像上面那样做(至少在Chrome中)。

我想这样做的原因是因为我在AngularJS中测试一个指令,操纵textarea,作为我测试的一部分,我想指定插入符号的位置。

如果不可能,是否有原因?还有在单元测试中设置插入符号的替代方法吗?

小提琴

var input = document.createElement("textarea");
// Add the manually created element to the document body
document.body.appendChild(input);
// Just added to confirm visually
input.textContent = "Something clever here";
input.selectionStart = 2; // returns 2
input.selectionEnd = input.textLength - 2;