<style>
.dotted {
width: 0px;
height: 0px;
background-color: none;
border: solid 3px rgb(5, 247, 37);
position: absolute;
left: 0px;
top: 0px;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="dotted"></div>
<script>
var dotted = document.getElementsByClassName('dotted')[0];
var downX = 0;//判断按下鼠标时的X位置
var downY = 0;//判断按下鼠标时的Y位置
var on_off = false;//开关【为了先点击后移动】
window.onmousedown = function (e) {
on_off = true;//开,可以移动
e = e || window.event;
downX = e.clientX;//获取按下鼠标时的X位置
downY = e.clientY;//获取按下鼠标时的Y位置
}
window.onmousemove = function (e) {
e = e || window.event;
if (on_off) {
var moveX = e.clientX;//鼠标移动的X位置
var moveY = e.clientY;//鼠标移动的Y位置
var box_width = Math.abs(moveX - downX);//根据x轴位置不同求出差值设置为width
var box_height = Math.abs(moveY - downY);//根据y轴位置不同求出差值设置为height
var box_top = 0;
var box_left = 0;
//由于鼠标可能移至起点的左侧和上侧,所以取到两者的最小值
box_left = Math.min(moveX, downX);
box_top = Math.min(moveY, downY);
//将数据写入样式
dotted.style = 'top:' + box_top + 'px;left:' + box_left + 'px;width:' + box_width + 'px;height:' + box_height + 'px;'
}
}
window.onmouseup = function (e) {
e = e || window.event;
on_off = false;
}
</script>
是不是 很神奇呢?