4

JavaScript 通过 preventDefault() 使 input[type=text] 禁止输入但保留光标

 2 years ago
source link: https://segmentfault.com/a/1190000041019591
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

取消事件的默认动作。该方法将通知 Web 浏览器不要执行与事件关联的默认动作(如果存在这样的动作)。例如,如果 type 属性是 submit,在事件传播的任意阶段可以调用任意的事件句柄,通过调用该方法,可以阻止提交表单。注意,如果 Event 对象的 cancelable 属性是 fasle,那么就没有默认动作,或者不能阻止默认动作。无论哪种情况,调用该方法都没有作用。

event.preventDefault()

3.1 阻止 <a> 元素跳转

<a href="http://www.mazey.net/baby/blog" target="_blank" id="a-prevent">点击我看会不会跳转</a>
<script>
document.getElementById('a-prevent').addEventListener('click',function(e){
    var eObj = e || window.event;
    eObj.preventDefault();
});
</script>

另外可以通过 return false; 来阻止 a 元素跳转事件。

<script>
    function preventGO(){
        return false;
    }
</script>
<a href="http://www.mazey.net/baby/blog/" onclick="return false;">点击我看会不会跳转1</a><br />
<a href="http://www.mazey.net/baby/blog/" onclick="preventGO();">点击我看会不会跳转2</a><br />
<a href="http://www.mazey.net/baby/blog/" onclick="return preventGO();">点击我看会不会跳转3</a>

3.2 禁止 <input> 元素键盘输入

<input type="text" id="input-prevent" placeholder="试试能不能输入" />
<script>
document.getElementById('input-prevent').addEventListener('keypress',function(e){
    var eObj = e || window.event;
    eObj.preventDefault();
});
</script>

版权声明

本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者后除和本文原始地址:https://blog.mazey.net/538.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK