<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<title>iPhone手机解锁效果</title>
<style type="text/css">
#iphone{position:relative;width:426px;height:640px;margin:10px auto;background:url(iphone.jpg) no-repeat;}
#lock{position:absolute;left:50%;bottom:33px;width:358px;height:62px;margin-left:-179px;}
#lock span{position:absolute;width:93px;height:62px;cursor:pointer;background:url(unlock_btn.jpg) no-repeat;}
</style>
</head>
<body>
<div id="iphone">
<div id="lock"><span></span></div>
</div>
</body>
</html>
<script type="text/javascript" src="sport.js"></script>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
var phone = $('iphone');
var lock = $('lock');
var ospan = lock.children[0];
var x;
var max;
ospan.onmousedown = function(e){
var e = e||window.event;
var disx = e.offsetX;
console.log(e.offsetX);//点击的地方距离span左边缘的距离
console.log(e.pageX);//点击的地方距离网页最左侧的距离
console.log(phone.offsetLeft);//phone距离body的左侧的距离
console.log(lock.offsetLeft);//lock距离phone的左侧的距离
ospan.onmousemove = function(e){
console.log(phone.offsetLeft);//phone距离body的左侧的距离
console.log(lock.offsetLeft);//lock距离phone的左侧的距离
x = e.pageX - phone.offsetLeft - lock.offsetLeft - disx;
console.log(x);
max = lock.offsetWidth - ospan.offsetWidth;
x = x<0?0:(x>max?max:x);
ospan.style.left = x + 'px';
}
ospan.onmouseup = function(e){
ospan.onmousemove = null;
var e = e || window.event;
if(x>=max/2){
console.log('123')
startMove(ospan,max,'left')
}else{
startMove(ospan,0,'left')
}
}
}
</script>
sport.js
function startMove(obj,target,attr){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var current = parseFloat(getStyle(obj,attr));
var speed = 0;
if(attr === 'opacity'){
speed = target-current>0?0.1:-0.1;
}else{
speed = (target - current)/10; //
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
}
if(target == current){
clearInterval(obj.timer);
}else{
if(attr === 'opacity'){
obj.style[attr] = current+speed;
}else{
obj.style[attr] = current+speed+'px';
}
}
},20)
}
//获取元素的属性
function getStyle(obj,attr){
if(window.getComputedStyle){
return window.getComputedStyle(obj,null)[attr];
}else{
return obj.currentStyle[attr];
}
}
//针对两种情况来进行一下整合
效果图