<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
#main{
position: absolute;
width: 600px;
height: 600px;
background-color: #999;
border:1px solid #ddd;
margin: 40px auto;
}
#main>div{
/* position: absolute;*/
width: 200px;
height: 200px;
float: left;
/* cursor:pointer;*/
}
#main div:nth-child(1){
position: absolute;
background-image: url(1.png)
}
#main div:nth-child(2){
position: absolute;
left: 200px;
background-image: url(9.png)
}
#main div:nth-child(3){
position: absolute;
left: 400px;
background-image: url(7.png)
}
#main div:nth-child(4){
position: absolute;
top: 200px;
background-image: url(8.png)
}
#main div:nth-child(5){
position: absolute;
left: 200px;
top: 200px;
background-image: url(2.png)
}
#main div:nth-child(6){
position: absolute;
left: 400px;
top: 200px;
background-image: url(3.png)
}
#main div:nth-child(7){
position: absolute;
top:400px;
background-image: url(4.png)
}
#main div:nth-child(8){
position: absolute;
left: 200px;
top: 400px;
background-image: url(5.png)
}
#main div:nth-child(9){
position: absolute;
left: 400px;
top: 400px;
background-image: url(6.png)
}
</style>
</head>
<body>
<div id="main">
<div></div
><div></div
><div></div
><div></div
><div></div
><div></div
><div></div
><div></div
><div></div>
</div>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
var boot =$(‘main‘).getElementsByTagName(‘div‘);
var imgstatic = 0;
for( i=0;i<boot.length;i++){
boot[i].onmousedown = function(){
imgstatic++;
var oevent = window.event || arguments[0];
var divnode= oevent.srcElement || oevent.target;
divnode.style.zIndex="999";
}
boot[i].onmousemove = function(){
var oevent = window.event || arguments[0];
// 获得 img 对象
var imgnode = oevent.srcElement || oevent.target;
if(imgstatic ==1){
var mousex = oevent.clientX;
var mousey = oevent.clientY;
console.log(mousey);
var mouseoffx = oevent.offsetX;
var mouseoffy = oevent.offsetY;
imgnode.style.top = mousey-100+‘px‘;
imgnode.style.left = mousex-100+‘px‘;
}
}
boot[i].onmouseup = function(){
imgstatic =0;
var oevent = window.event || arguments[0];
var divnode= oevent.srcElement || oevent.target;
divnode.style.zIndex="0";
}
boot[i].onmouseout = function(){
imgstatic =0;
}
}
</script>
</body>
</html>
JavaScript实现的拼图