JavaScript 默认行为

来源:互联网 发布:阿里云服务器怎么部署 编辑:程序博客网 时间:2024/06/16 18:52

默认行为
什么是默认行为
阻止默认行为
普通写法:return false;

阻止表单提交:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>window.onload=function (){    var oForm=document.getElementById('form1');    oForm.onsubmit=function ()    {        return false;    };};</script></head><body><form id="form1" action="http://www.miaov.com/">    <input type="submit" /></form></body></html>

例子1. 屏蔽右键菜单
弹出自定义右键菜单

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style>* {margin:0; padding:0;}#ul1 {width:100px; background:#CCC; border:1px solid black; position:absolute; display:none;}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>document.oncontextmenu=function (ev){    var oEvent=ev||event;    var oUl=document.getElementById('ul1');    oUl.style.display='block';    oUl.style.left=oEvent.clientX+'px';    oUl.style.top=oEvent.clientY+'px';    return false;};document.onclick=function (){    var oUl=document.getElementById('ul1');    oUl.style.display='none';};</script></head><body><ul id="ul1">    <li>登陆</li>    <li>回到首页</li>    <li>注销</li>    <li>加入VIP</li></ul></body></html>

例子2. 只能输入数字的输入框
keydown、keyup事件的区别

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>window.onload=function (){    var oTxt=document.getElementById('txt1');    oTxt.onkeydown=function (ev)    {        var oEvent=ev||event;        //alert(oEvent.keyCode);        //0     48        //9     57        //退格    8        if(oEvent.keyCode!=8 && (oEvent.keyCode<48 || oEvent.keyCode>57))        {            return false;        }        //return false;    };};</script></head><body><input id="txt1" type="text" /></body></html>

参考:JavaScript

阅读全文
0 0
原创粉丝点击