事件 绑定,取消冒泡,拖拽 ,点击,事件委托习题
2019-03-11 18:08 HHFFZ 阅读(378) 评论(0) 编辑 收藏 举报事件知识的,冒泡,绑定,委托
<script type="text/javascript"> //事件绑定 取消 var div=document.getElementsByTagName('div')[0]; div.addEventListener('click',test,false); div.removeEventListener('click', test,false); function test(){ console.log('a'); } //取消冒泡; document.onclick=function(){ console.log('全局'); } div.addEventListener("click",function(e){ this.style.background='green'; // e.stopPropagation(); e.cancelBubble=true; },false) //事件委托;利用事件冒泡和事件原对象 var ul=document.getElementsByTagName('ul')[0]; ul.onclick=function(e){ var event =e||window.event; var target=event.target||event.srcElement; console.log(target.innerText); }
习题小练习
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style text="text/css"> input{ border:1px solid #01f; } div{ margin: 100px; } </style> </head> <body> <input type="text" value="请输入用户名" style="color:#999" onfocus="if(this.value=='请输入用户名') { this.value=''; this.style.color='red'; }" onblur="if(this.value==''){ this.value='请输入用户名'; this.style.color='#999' }"> <div class="box" style="height: 100px; width:100px; background-color:red; position: absolute; left:10px; top: 0;" ></div> <script type="text/javascript">//拖拽练习 var div=document.getElementsByTagName('div')[0]; var disx,disy; div.onmousedown=function(e){ disx=e.pageX-parseInt(div.style.left); disy=e.pageY-parseInt(div.style.top); document.onmousemove=function(e){ var event=e||window.event; div.style.left=e.pageX-disx+"px"; div.style.top=e.pageY-disy+"px"; } document.onmouseup=function(){ document.onmousemove=null; } } //返回按键字母 document.onkeypress=function(e){ console.log(String.fromCharCode(e.charCode)); } </script> </body> </html>