[英]Disable Paste action using Javascript (without include Jquery)
I have a text box for the login mobile number, I have to disable the paste action我有一个用于登录手机号码的文本框,我必须禁用粘贴操作
Am working in ReactJs, The code that I used is Mention below.我在 ReactJs 工作,我使用的代码是下面提到的。
<input
type="text"
name="userName"
placeholder="Mobile number"
onChange={e => this.onChangeNumber(e)}
value={this.state.userName}
maxLength="10"
autoFocus
autoComplete="off"
/>
I want to disable the paste action using the JS code without using jquery and any other packages.我想在不使用 jquery 和任何其他包的情况下使用 JS 代码禁用粘贴操作。 Anyone help me to complete this.
任何人都可以帮助我完成这个。
Thanks in Advance.提前致谢。
If you are using the reactjs, you can directly use the onPaste event in the input tag as given below.如果您使用的是 reactjs,您可以直接在输入标签中使用 onPaste 事件,如下所示。 So it will restrict the paste action.
所以它会限制粘贴动作。
<input
type="text"
name="userName"
placeholder="Mobile number"
onChange={e => this.onChangeNumber(e)}
onPaste={e => {e.preventDefault()}}
value={this.state.userName}
maxLength="10"
autoFocus
autoComplete="off"
/>
If you want use the js, you can use the following code in your function.如果要使用 js,可以在 function 中使用以下代码。 So that the paste action will get prevented.
这样粘贴动作就会被阻止。
onChangeNumber =()=>{
document.getElementByName('userName').onpaste=function(e){
e.preventDefault();
}
}
One of the many ways to do this is like做到这一点的众多方法之一是
useEffect(()=>{
document.getElementById('ipt').onpaste=function(e){
e.preventDefault();
}
},[])
return (
<div className="App">
<input
type="text"
name="userName"
placeholder="Mobile number"
id='ipt'
autoFocus
autoComplete="off"
/>
</div>
);
}
Why useEffect used?为什么要用useEffect? So, that the DOM element input has initialised and does not return NULL when we
document.getElementById
it.因此,当我们
document.getElementById
时,DOM 元素输入已经初始化并且不会返回 NULL。
NOTE: It is generally not advisable to restrict pasting to an input field.注意:通常不建议将粘贴限制在输入字段中。 It is annoying and affects the User Experience.
这很烦人并影响用户体验。
PS: I am not exactly sure why refs dont work with onpaste. PS:我不确定为什么 refs 不能与 onpaste 一起使用。 maybe that would be a better REACT ish way of doing it.
也许这将是一种更好的REACT方式。
<input
type="text"
name="userName"
placeholder="Mobile number"
onChange={e => this.onChangeNumber(e)}
onPaste={e => {e.preventDefault()}}
value={this.state.userName}
maxLength="10"
autoFocus
autoComplete="off"
/>
Simply preventing default action onPaste would do needful.简单地阻止 onPaste 的默认操作是必要的。
<input type="text" class="word"> //html code
let box = document.querySelector(".word");// javacript method
//Disable Paste Event
box.onpaste = function () {
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.