原生js实现照片墙的效果(拖拽图片与另一张图片交换位置)
程序员文章站
2022-05-23 09:24:30
...
用到的功能有:
- 布局转换(将float布局转换为定位布局)
- 图片拖拽效果的实现
- 碰撞检测
- 计算两点之间的斜线距离
- 找最小值
具体的实现在代码中我都有注释,嗯,直接上代码。
注:这里还需要有一个运动框架,需要的请点击js运动框架
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin:0px; padding:0px;}
#box{width:340px; height:340px; margin:100px auto;}
#box img{width:100px; height:100px; margin-left:10px; margin-top:10px;}
</style>
</head>
<body>
<div id="box">
<img src="photo/a.jpg"/>
<img src="photo/b.jpg"/>
<img src="photo/c.jpg"/>
<img src="photo/d.jpg"/>
<img src="photo/e.jpg"/>
<img src="photo/f.jpg"/>
<img src="photo/g.jpg"/>
<img src="photo/h.jpg"/>
<img src="photo/j.jpg"/>
</div>
<script src="move.js"></script>
<script>
var oDiv = document.getElementById('box');
var aImg = oDiv.getElementsByTagName('img');
var arr=[];
var zIndex = 2;
for(var i=0; i<aImg.length; i++){//记录每一张图片的left和top的值
arr.push([aImg[i].offsetLeft,aImg[i].offsetTop]);
}
for(var i=0; i<aImg.length; i++){//布局转换,将float布局转换为定位布局
aImg[i].style.position = 'absolute';
aImg[i].style.left = arr[i][0]+'px';
aImg[i].style.top = arr[i][1]+'px';
aImg[i].style.margin = 0;
}
for(var i=0; i<aImg.length; i++){
aImg[i].index = i;
drag(aImg[i]);
}
function drag(obj){//为每一张图片设置拖拽的功能
obj.onmousedown = function(ev){
var ev = ev||event;
obj.style.zIndex = zIndex++;
var disX = ev.clientX - obj.offsetLeft;
var disY = ev.clientY - obj.offsetTop;
document.onmousemove = function(ev){
obj.style.left = ev.clientX - disX +'px';
obj.style.top = ev.clientY - disY + 'px';
for(var i=0; i<aImg.length; i++){
aImg[i].style.border = '';
}
if(bian(obj)){
bian(obj).style.border = '2px solid yellow';
}
}
document.onmouseup = function(){
document.onmousemove = document.onmouseup = null;
var nImg = bian(obj);
var tem = 0;
if(nImg){
startMove(nImg,{left:arr[obj.index][0],top:arr[obj.index][1]});
startMove(obj,{left:arr[nImg.index][0],top:arr[nImg.index][1]});
tem = obj.index;//改变索引值
obj.index = nImg.index;
nImg.index = tem;
nImg.style.border = '';
}else{
startMove(obj,{left:arr[obj.index][0],top:arr[obj.index][1]});
}
}
return false;
}
}
function bian(obj){//找最小值
var value = 9999;
var index = -1;
for(var i=0; i<aImg.length; i++){
if(closer(obj,aImg[i])&&obj!=aImg[i]){
var c = getdis(obj,aImg[i]);
if(c<value){
value = c;
index = i;
}
}
}
if(index !=-1){
return aImg[index];
}else{
return false;
}
}
function getdis(obj1,obj2){//两点之间的距离
var a = obj1.offsetLeft - obj2.offsetLeft;
var b = obj1.offsetTop - obj2.offsetTop;
return Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
}
function closer(obj1,obj2){//碰撞检测
var L1 = obj1.offsetLeft;
var R1 = obj1.offsetLeft + obj1.offsetWidth;
var T1 = obj1.offsetTop;
var B1 = obj1.offsetTop+obj1.offsetHeight;
var L2 = obj2.offsetLeft;
var R2 = obj2.offsetLeft + obj2.offsetWidth;
var T2 = obj2.offsetTop;
var B2 = obj2.offsetTop+obj2.offsetHeight;
if(L1>R2||R1<L2||T1>B2||B1<T2){
return false;
}else{
return true;
}
}
</script>
</body>
</html>
下一篇: C#中Where及Select使用