<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.pen{
width: 10px;
height: 10px;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<script>
// 设置点击事件
let bodys = document.querySelector("body")
var ml=0;
var down_x=0;
var down_y=0;
var up_x=0;
var y_x=0;
var down_t=0;
document.onmousedown = function(e){
down_x=e.clientX;
down_y=e.clientY;
//按下鼠标的时候才开始绘制点
document.onmousemove = function(eve){
// 位置坐标用于数组
let pos = {
//取得鼠标坐标
cx: eve.clientX,
cy: eve.clientY,
}
//绘制元素点
new Draw(bodys,pos);
ml+=1;
down_t = new Date().getTime();
//alert(pos.cx+","+pos.cy);
document.getElementById('res_display').innerHTML="mouse move num="+ml+","+down_t;
}
}
//抬起清空事件
document.onmouseup = function(e){
document.onmousemove = "";
//alert("mouse move num="+ml);
document.getElementById('res_display').innerHTML="mouse move num="+ml+"</br>" +
'mouse_down:'+down_x+","+down_y+"</br>"+
'mouse_up:'+e.clientX+","+e.clientY+"</br>"+
't='+((new Date().getTime())-down_t); //+eve.clientX;
}
function Draw(bodys,pos){
//设置属性值
this.body = bodys;
this.pos = pos;
//生成div
let divObj = document.createElement("div");
divObj.classList.add('pen');
divObj.style.left = this.pos.cx + "px";
divObj.style.top = this.pos.cy + "px";
divObj.style.background = this.getColor();
this.body.appendChild(divObj);
}
//随机数生成方法
Draw.prototype.rand = function(min,max){
return Math.round(Math.random()*(max-min)+min);
}
//随机颜色生成方法
Draw.prototype.getColor = function(){
let colors = "#";
for(let i=0 ; i<6 ; i++){
colors+=this.rand(0,15).toString(16);
}
return colors;
}
</script>
<div style="position:relative">
<div style="position:absolute;left:0px;top:0px;background-color:yellow" id='res_display'>
res display here:mouse move and click up and down
</div>
</div>
</body>
html鼠标事件获取
最新推荐文章于 2023-10-18 10:32:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)