javascript ---IPhone滑动解锁
<script type="text/javascript"> var untilEvent = { addEvent:function(oElement,oType,fun){ oElement.attachEvent?oElement.attachEvent("on"+oType,fun):oElement.addEventListener(oType,fun,false); }, removeEvent:function(oElement,oType,fun){ oElement.detachEvent?oElement.detachEvent("on"+oType,fun):oElement.removeEventListener(oType,fun,false); } } window.onload = function(){ var oPar = document.getElementById("iphone"); var oDiv = document.getElementById("lock"); var oSpan = oDiv.getElementsByTagName("span")[0]; var spanW = oSpan.offsetWidth; var divW = oDiv.offsetWidth; var downX = 0; var moveX = 0; var movekg = true; var mDown = function(event){ var ev = event || window.event; downX = ev.clientX; untilEvent.addEvent(oSpan,"mousemove",mMove); untilEvent.addEvent(document,"mouseup",mUp); if(event.preventDefault){ event.preventDefault(); event.stopPropagation(); } } var mMove = function(event){ ev = event || window.event; if(ev.cancelBubble){ ev.cancelBubble=true; ev.returnValue = false; } moveX = ev.clientX; var moveLenght = moveX - downX; if(moveLenght>0){moveLenght = Math.min(moveLenght,divW-spanW)}else{ moveLenght = 0; } oSpan.style.left = moveLenght+"px"; } var mUp = function(){ untilEvent.removeEvent(oSpan,"mousemove",mMove); untilEvent.removeEvent(document,"mouseup",mUp); if(oSpan.offsetLeft>=(divW-spanW)){ oPar.style.background = "url('http://fgm.cc/iphone/2.jpg')"; oSpan.style.background = "none"; } var dirct = oSpan.offsetLeft>(divW/2-spanW+20)?true:false; var setInt = setInterval(function(){ if(dirct){ oSpan.style.left = Math.min(divW-spanW,(oSpan.offsetLeft + 15))+"px"; if(oSpan.offsetLeft >= (divW-spanW)){ oPar.style.background = "url('http://fgm.cc/iphone/2.jpg')"; oSpan.style.background = "none"; clearInterval(setInt); } }else{ oSpan.style.left = Math.max(0,(oSpan.offsetLeft - 15))+"px"; oSpan.offsetLeft <= 0 && clearInterval(setInt); } },30) } untilEvent.addEvent(oSpan,"mousedown",mDown); } </script>
一、实现功能
1.在滑块移动到中间时向左自动,滑到起始点
2.当滑块超过中间时,向右自动,滑到终点,并解锁
3.鼠标拖动滑块到终点解锁
二、注意点
1.去掉鼠标拖动时的默认事件
可以参看我博客里面随笔
2.控制滑块的区域,可以用Math.MAx或Marh.Min
3.在使用Setinterval时,注意区别两种不同情况