<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>拖放</title>
<style>
#box{
width: 150px;
height:150px;
background-color: rgba(255,0,255,.5);
position: absolute;
left: 0px;
top: 0px;
/*border-radius: 50%;*/
z-index: 10;
cursor:pointer;
}
#box1{
width: 150px;
height:150px;
background-color: rgba(0,0,255,.5);
position: absolute;
left: 50%;
top: 50%;
/*border-radius: 50%;*/
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<!--被拖動元素-->
<div id="box"></div>
<!--目標元素-->
<div id="box1"></div>
<!--顯示重疊面積百分比-->
<p id="p1"></p>
<!--音頻播放器-->
<audio id="audio">
<source src="Colbie Caillat - Try.mp3" type="audio/mp3" />
<source src="song.ogg" type="audio/ogg" />
Your browser does not support this audio format.
</audio>
<script>
var box = document.getElementById('box');
var box1 = document.getElementById('box1');
var body = document.getElementsByTagName('body')[0];
var p = document.getElementById('p1');
var audio = document.getElementById('audio');
function bindEvent(ele,warp){
var X,//鼠標點擊所在x方向偏移
Y,//鼠標點擊所在Y方向偏移
boxL,//所拖動元素距離屏幕左側偏移
boxT,//所拖動元素距離屏幕上側偏移
disL,//鼠標點擊位置距離所拖動元素左側偏移
disT,//鼠標點擊位置距離所拖動元素上側偏移
drap = false;//判定元素是否拖動;
//獲取元素尺寸
var boxWidth = box.offsetWidth,
boxHeight = box.offsetHeight,
box1Width = box1.offsetWidth,
box1Height = box1.offsetHeight;
//鼠標按下事件
ele.onmousedown = function(e){
var event = e || window.event;
drap = true;
X = event.clientX;
Y = event.clientY;
boxL = ele.offsetLeft;
boxT = ele.offsetTop;
disL = X - boxL;
disT = Y - boxT;
};
//鼠標拖動事件
warp.onmousemove = function(e){
var event = e || window.event;
if(drap){
ele.style.left = event.clientX - disL + 'px';
ele.style.top = event.clientY - disT + 'px';
var overlapWidth = 0,//重疊區域width
overlapHeight = 0,//重疊區域height
L = ele.offsetLeft,
T = ele.offsetTop,
L1= box1.offsetLeft,
T1 = box1.offsetTop;
// console.log(L,L1)
if((L+boxWidth>=L1) && (L+boxWidth < L1+ box1Width)){
overlapWidth = (L+boxWidth - L1) > boxWidth?boxWidth:(L+boxWidth - L1);
}else if(L+boxWidth >= L1+box1Width && L < L1+box1Width){
overlapWidth = L1+box1Width - L;
}
if((T+boxHeight >= T1) && (T+boxHeight < T1+box1Height)){
overlapHeight = (T+boxHeight - T1) > boxHeight?boxHeight:(T+boxHeight - T1);
}else if((T+boxHeight >= T1+box1Height) && (T < T1+box1Height)){
overlapHeight = T1+box1Height - T;
}
var html = (((overlapWidth*overlapHeight)/(box1Width*box1Height))).toFixed(2);
p.innerHTML = audio.volume = html;
html>0? audio.play():audio.pause();
}
};
//鼠標按出事件
ele.onmouseup = function (){
drap = false;
};
}
bindEvent(box,body);
</script>
</body>
</html>