首页 > 代码库 > javascript-事件冒泡、鼠标跟随、键盘跟随、键盘提交
javascript-事件冒泡、鼠标跟随、键盘跟随、键盘提交
1、事件冒泡
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css" media="screen"> #d1 {width: 200px;height: 300px;background: #CCC ; display: none;} </style> <script> window.onload=function(){ var ob=document.getElementById(‘b1‘) var od=document.getElementById(‘d1‘) //document > ! + HTML //IE // alert(‘click:‘+event.clientX+‘,‘+event.clientY) //FF // alert(‘click:‘+event.clientX+‘,‘+event.clientY) ob.onclick=function (event) { od.style.display=‘block‘ //取消event冒泡, event.cancelBubble=true } document.onclick=function () { od.style.display=‘none‘ } } </script> </head> <body> <!-- table[id=‘tb1‘ border="1" width="500">thead>td*3+tbody>(tr>td*3)*3 --> <input type="button" value="http://www.mamicode.com/button" id="b1"> <div id="d1"></div> </body> </html>
2、鼠标跟随
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css" media="screen"> #div1 {width: 200px;height: 200px;background: #CCC;position: absolute;} </style> <script type="text/javascript"> document.onmousemove=function(event){ var od=document.getElementById(‘div1‘) //clientX/clientY 坐标是可视区域内的坐标; var scrollTop=document.documentElement.scrollTop||document.body.scrollTop var pos=getPos(event) od.style.left=pos.x+‘px‘ od.style.top=pos.y+scrollTop+‘px‘ } function getPos(event) { var scrollTop=document.documentElement.scrollTop||document.body.scrollTop var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft return {x:event.clientX+scrollLeft,y:event.clientY+scrollTop} } </script> </head> <body> <div id="div1"></div> </body> </html>
3、键盘跟随移动
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css" media="screen"> #div1 {width: 200px;height: 200px;background: #CCC;position: absolute;} </style> <script> document.onkeydown=function(event){ // alert(event.keyCode) var od=document.getElementById(‘div1‘) if (event.keyCode==37) { od.style.left=od.offsetLeft-10+‘px‘ }else if(event.keyCode==39){ od.style.left=od.offsetLeft+10+‘px‘ } } </script> </head> <body> <div id="div1"></div> </body> </html>
4、键盘事件提交
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css" media="screen"> #div1 {width: 200px;height: 200px;border: 1px solid #000;position: absolute;} </style> <script> document.onkeydown=function(event){ // alert(event.keyCode) var od=document.getElementById(‘div1‘) var ot=document.getElementById(‘t1‘) var ob=document.getElementById(‘b1‘) // 事件提交 ob.onclick=function(){ od.innerHTML+=ot.value+‘<br>‘ ot.value=http://www.mamicode.com/‘‘"text" name="" id="t1"> <input type="button" value="http://www.mamicode.com/提交" id="b1"> <div id="div1"></div> </body> </html>
javascript-事件冒泡、鼠标跟随、键盘跟随、键盘提交
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。