gpt4 book ai didi

javascript - 为什么某些输入元素具有 setSelectionRange 属性以及如何测试它是否确实受支持?

转载 作者:行者123 更新时间:2023-12-01 04:04:45 24 4
gpt4 key购买 nike

我很确定我曾经测试过 setSelectionRange 属性的复选框,但他们没有。但在某些浏览器中,情况似乎发生了变化(已测试 Firefox 和 Chrome)。

我过去常常在进行如下选择之前检查 setSelectionRange 属性:

if (el.setSelectionRange) {
el.setSelectionRange(0, 9999);
}

但是,由于复选框似乎具有 setSelectionRange 属性,因此会引发错误。

那么我现在如何测试是否可以进行选择?

这也是一个 fiddle :

https://jsfiddle.net/kb2ad5b5/

一些背景

该测试是在父级的委托(delegate)事件监听器中进行的,该监听器选择可以执行此操作的任何元素中的范围。

最佳答案

他们有一个setSelectionRange,因为该方法是在 HTMLInputElement interface 中定义的。 ,因此所有输入都会继承它,即使它们是复选框。

但是当然setSelectionRange不适用于所有输入,在这种情况下它会抛出:

For input elements, calling these methods while they don't apply, and setting these attributes while they don't apply, must throw an "InvalidStateError" DOMException; and getting these attributes while they don't apply must return null. Otherwise, they must act as described below.

仅适用于Text, Search , URL , TelephonePassword输入。

所以你可以做类似的事情

if (["text", "search", "url", "tel", "password"].indexOf(input.type) >= 0) {
input.setSelectionRange(start, end);
}

或者,您可以使用 try-catch 语句:

try {
input.setSelectionRange(start, end);
} catch(err) {
if (err instanceof DOMException && err.name === "InvalidStateError") {
// setSelectionRange does not apply
} else {
throw err;
}
}

关于javascript - 为什么某些输入元素具有 setSelectionRange 属性以及如何测试它是否确实受支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41919460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com