首页 > 代码库 > 默认行为(默认事件)

默认行为(默认事件)

一、阻止默认行为:

    return false;

    例如:屏蔽右键菜单,弹出自定义右键菜单

     

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        #div1 {
            width: 80px;
            background: #ccc;
            position: absolute;
            display: none;
        }
    </style>
    <script>
       document.oncontextmenu = function (ev) {
           oEvent = ev || event;
           var oDiv = document.getElementById(‘div1‘);
           oDiv.style.display = ‘block‘;
           //div的位置跟着鼠标的位置出现
           oDiv.style.left = oEvent.clientX + ‘px‘;
           oDiv.style.top = oEvent.clientY + ‘px‘;
           return false;//屏蔽右键默认菜单
       };
       //点击空白取消自定义菜单
       document.onclick = function () {
           var oDiv = document.getElementById(‘div1‘);
           oDiv.style.display = ‘none‘;
       };
    </script>
</head>

<body>
<div id="div1">
    <ul>
        <li>aaaa</li>
        <li>bbbb</li>
        <li>cccc</li>
        <li>dddd</li>
    </ul>
</div>
</body>
</html>

 二、只能输入数字的输入框  (在英文输入状态下)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
    </style>
    <script>
       window.onload = function () {
           var oText1 = document.getElementById(‘text1‘);
           oText1.onkeydown = function (ev) {
               var oEvent = ev || event;
               //只能输入数字的输入框 0为48,9为57,删除键为8
               if(oEvent.keyCode!= 8 &&(oEvent.keyCode<48||oEvent.keyCode>57)){
                   return false;//不为数字不能输入
               }
           };
       };
    </script>
</head>

<body>
  <input type="text" id="text1">
</body>
</html>

 

默认行为(默认事件)