介绍
实现拖放效果有两种,一种是利用drag事件实现,一种是利用鼠标事件实现,我这里采用鼠标事件实现。
主要用到的事件:mousemove(鼠标移动),mouseup(鼠标按下),mousedown(鼠标抬起)
当点击dom的时候,记录当前鼠标的坐标值,也就是x、y值,以及被拖拽的dom的top、left值,
在鼠标按下的回调函数里添加鼠标移动的事件;
并且添加鼠标抬起事件,为了解除鼠标移动的监听,因为只有在鼠标按下才可以拖拽,抬起就停止不会移动了。
布尔值参数:表示 listener
在添加之后最多只调用一次。如果为 true
,listener
会在其被调用之后自动移除。
当鼠标按下鼠标移动的时候,记录移动中的x、y值,那么这个被拖拽的dom的top和left值就是:
top=鼠标按下时记录的dom的top值+(移动中的y值 - 鼠标按下时的y值)
left=鼠标按下时记录的dom的left值+(移动中的x值 - 鼠标按下时的x值);
代码
dom.addEventListener("mousedown",
function(event){
var x=event.clientX;
var y=event.clientY;
var marginleft = parseInt(dom.offsetLeft);
var margintop = parseInt(dom.offsetTop);
function moving(e){
var movedX = e.clientX-x
var movedY = e.clientY-y
dom.style.marginLeft=marginleft + movedX + "px"
dom.style.marginTop= margintop + movedY + "px"
}
document.addEventListener("mousemove",moving,false)
document.addEventListener("mouseup",function(){
document.removeEventListener("mousemove",moving,false)
},false)
},
false
)
实现在棋盘上拖放棋子效果页面:
<!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>
</head>
<style>
.q{
width: 75px;
height: 75px;
background-color: aqua;
border-radius: 50%;
position: absolute;
top: 10px;
left: 10px;
z-index: 999;
}
</style>
<body>
<canvas id="myCanvas" width="600px" height="660px"></canvas>
<div class="q" id="q">
</div>
</body>
<script>
var chessCanvas=document.getElementById("myCanvas");
var chessContext=chessCanvas.getContext("2d");
drawBoard();
function drawBoard(){
chessContext.clearRect(0,0,600,600)
var gradient=chessContext.createLinearGradient(0,600,600,0)
gradient.addColorStop(0,"#d50005")
gradient.addColorStop(0.5,"#e27883")
gradient.addColorStop(1,"#ffdddd")
chessContext.fillStyle=gradient;
chessContext.strokeStyle="red";
for(var x=0;x<8;x++){
for(var y=0;y<8;y++){
if((x+y)%2){
chessContext.fillRect(75*x,75*y,75,75);
}
}
}
}
chessContext.strokeRect(0,0,600,600);
window.onload=function(){
var dom=document.getElementById("q")
dom.addEventListener("mousedown",
function(event){
var x=event.clientX;
var y=event.clientY;
var marginleft = parseInt(dom.offsetLeft);
var margintop = parseInt(dom.offsetTop);
function moving(e){
var movedX = e.clientX-x
var movedY = e.clientY-y
dom.style.marginLeft=marginleft + movedX + "px"
dom.style.marginTop= margintop + movedY + "px"
}
document.addEventListener("mousemove",moving,false)
document.addEventListener("mouseup",function(){
document.removeEventListener("mousemove",moving,false)
},false)
},
false
)
}
</script>
</html>