javascript - 使用“Ctrl+A”全选并删除输入字段的内容
问题描述
我正在为社会安全号码创建一个输入字段,但输入字段的功能存在问题。我希望能够在 Mac 上按“Ctrl + A”或“Command + A”来选择输入字段的内容,然后将其删除。我无法在带有 Chrome 的 Windows 10 上执行此操作。关于修改什么以允许这种行为的任何想法?
这是一个代码框:https ://codesandbox.io/s/tel-formating-forked-3uz9q?file=/src/App.js
这是相关的代码:
//App.js
import React, { useRef, useState, useLayoutEffect } from "react";
export default function App() {
const [state, setState] = useState({ phone: "" });
const cursorPos = useRef(null);
const inputRef = useRef(null);
const keyIsDelete = useRef(false);
const handleChange = (e) => {
cursorPos.current = e.target.selectionStart;
let val = e.target.value;
cursorPos.current -= (
val.slice(0, cursorPos.current).match(/-/g) || []
).length;
let r = /(\D+)/g,
first3 = "",
next3 = "",
last4 = "";
val = val.replace(r, "");
let newValue;
if (val.length > 0) {
first3 = val.substr(0, 3);
next3 = val.substr(3, 2);
last4 = val.substr(5, 4);
if (val.length > 5) {
newValue = first3 + "-" + next3 + "-" + last4;
} else if (val.length > 3) {
newValue = first3 + "-" + next3;
} else if (val.length < 4) {
newValue = first3;
}
} else newValue = val;
setState({ phone: newValue });
for (let i = 0; i < cursorPos.current; ++i) {
if (newValue[i] === "-") {
++cursorPos.current;
}
}
if (newValue[cursorPos.current] === "-" && keyIsDelete.current) {
cursorPos.current++;
}
};
const handleKeyDown = (e) => {
const allowedKeys = [
"Control",
"Delete",
"ArrowLeft",
"ArrowRight",
"Backspace",
"Home",
"End",
"Enter",
"Tab"
];
if (e.key === "Delete") {
keyIsDelete.current = true;
} else {
keyIsDelete.current = false;
}
if ("0123456789".includes(e.key) || allowedKeys.includes(e.key)) {
} else {
e.preventDefault();
}
};
useLayoutEffect(() => {
if (inputRef.current) {
inputRef.current.selectionStart = cursorPos.current;
inputRef.current.selectionEnd = cursorPos.current;
}
});
return (
<div className="App">
<input
ref={inputRef}
type="text"
value={state.phone}
placeholder="SSN"
onChange={handleChange}
onKeyDown={handleKeyDown}
/>
</div>
);
}
解决方案
您需要为 mac 添加“Meta”(而不是 control)和“a”来检测在按 control 到 allowedKeys 数组后实际发生的情况。问题是即使控制也不允许“a”键本身。
const allowedKeys = [
"Control",
"Delete",
"ArrowLeft",
"ArrowRight",
"Backspace",
"Home",
"End",
"Enter",
"Tab",
"Meta",
"a"
];
推荐阅读
- java - 如何将文本文件 (txt) 写入我的 ftp 服务器?
- plotly - 在 Dash 中更新图表(Plotly)
- python - ImportError:DLL 加载失败,使用 import sklearn
- java - 意外的 UI 行为
- c - 如何存储循环中的数组输出而不打印它
- php - Swift POST 方法和 PHP 不说话
- python - 只遍历数组中能被当前元素整除的元素
- tkinter - 此代码显示错误:-- AttributeError: 'NoneType' object has no attribute 'get'
- c - Printf 让程序卡住而没有响应
- django - 无法在 powershell 中运行 pipenv install django==2.1(或者 cmd),为什么?