• 当前标签:表单事件

程序开发 JavaScript 表单事件

<!DOCTYPE html> <html>     <head>         <meta charset="UTF-8">         <meta name="viewport" content="width=device-width, initial-scale=1.0">         <meta http-equiv="X-UA-Compatible" content="ie=edge">         <title>表单事件</title>         <style>         </style>     </head>     <body>         <form action="">             <input type="text" name="" value="">             <input type="submit" value="提交">             <input type="reset" value="重置/清空数据">         </form>         <script>             var input = document.querySelector('input[type=text]')             input.addEventListener('focusin',function(){                 // focusin获取焦点的时候触发                 console.log('focusin')             })             input.addEventListener('focus',function(){                 // focus获取焦点的时候触发                 console.log('focus')             })             input.addEventListener('focusout',function(){                 console.log('focusout')             })             input.addEventListener('blur',function(){                 console.log('blur')             })             // focus/blur 支持较好             // 而focusin和focusout 支持不好(调用顺序不同)             // focus 指的是获取输入焦点             // blur 输入焦点离开             input.addEventListener('change',function(){                 console.log('change')             })             // 文本框失去焦点检查内容 如果内容发生了变化则触发change事件             // 如果希望在输入时立即检查则应使用其他方式             input.addEventListener('select',function(){                 console.log('selectd')             })             // 选择输入框内的文本时触发             document.forms[0].addEventListener('submit',function(e){                 if(input.value.length>0){                     alert('可以提交')                 }                 else{                     alert('请输入')                     e.preventDefault()                     // 阻止默认事件                 }             })             // submit指表单提交之前 可以在这个事件中检查用户的输入是否合适             // 如果不合适则可以使用 event 的 preventDefaul() 来阻止表单提交             document.forms[0].addEventListener('reset',function(e){                 if(confirm('确定清空表单内容吗?')){                     // confirm弹出一个确认框 确认框有两个按钮                     // 点确定时confirm会返回true                     // 点取消时confirm会返回false                 }                 else{                     e.preventDefault()                     // 可以阻止表单被清空                 }             })         </script>     </body> </html>

2017-07-21 02:32:23 65 0 0
阅读详情
  • 1
前往