<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>鼠标拖拽</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box{
width: 400px;
height: 50px;
background: gray;
position: relative;
}
#box1{
width: 50px;
height: 50px;
background: red;
position: absolute;
left: 0;
top: 0;
}
#box2{
width: 400px;
height: 400px;
background: green;
opacity: 0;
}
</style>
</head>
<body>
<div id="box">
<div id="box1">
</div>
</div>
<div id="box2">
</div>
<script type="text/javascript">
var box = document.getElementById('box');
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
var w = box.offsetWidth - box1.offsetWidth;
var h = box.offsetHeight - box1.offsetHeight;
box1.onmousedown = function(){
var selfX = event.clientX - this.offsetLeft;
var selfY = event.clientY - this.offsetTop;
document.onmousemove = function(){
var newLeft = event.clientX - selfX;
var newTop = event.clientY - selfY;
if (newLeft<=0){
newLeft = 0;
}else if(newLeft>= w){
newLeft =w + "px";
}
box1.style.left = newLeft +'px'
box2.style.opacity = newLeft/w;
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
</body>
</html>
简单的鼠标拖拽(1)颜色渐变
最新推荐文章于 2021-07-17 00:05:33 发布