这个月一直再弄一件作品,需要大量的运用javascript语言,学习之余也把自己的代码与大家分享。
以下的javascript主要是完成,鼠标在网页中长时间按住不动,所发生的反应,此处的反应就是在鼠标坐标处,生成一个黑框。
<html> <head> <script> var secondTime = 3; //长按300 毫秒后做出相应的反应,此处是弹出一个黑框 var timeFlag = false; function blackBox(x,y){ //长按后调用生成黑框的方法 var box = document.createElement('div'); box.className = 'divT'; box.id = 'mouseBox'; box.style.top = y - 50; box.style.left = x - 50; document.body.appendChild(box); } function mouseStay(x,y){ if(secondTime == 0){ blackBox(x,y); }else if(timeFlag){ secondTime--; setTimeout( //长按事件时间的处理 (function(px,py){ return function(){ mouseStay(px,py); } })(x,y), 100 ); } } window.onload = function(){ document.onmousedown = function(event){ //事件使用函数需要有个event的参数 if(document.body.lastChild.id == 'mouseBox') document.body.removeChild(document.body.lastChild); timeFlag = true; mouseStay(event.clientX,event.clientY); } document.onmouseup = function(){ timeFlag = false; secondTime = 3; } } </script> <style> *{ margin:0; padding:0; } .divT{ float:left; width:100px; height:100px; background:#000; position:absolute; } </style> </head> <body> </body> </html>