setSelectionRange()
MDN
官方文档:HTMLInputElement.setSelectionRange() - Web API 接口参考 | MDN
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function selectText() {
const input = document.getElementById('text-box');
input.focus();
// 设置选区
// input.setSelectionRange(2, 5);
input.setSelectionRange(-1, -1);
// input.setSelectionRange(4, 7);
}
</script>
</head>
<body>
<input type="text" id="text-box" size="20" value="www.xxx.com">
<button onclick="selectText()">Select text</button>
</body>
</html>