javascript 實現(xiàn) 原路返回
更新時間:2015年01月21日 09:55:07 投稿:hebedich
這篇文章主要介紹了javascript 實現(xiàn)原路返回的方法,需要的朋友可以參考下
css代碼
復制代碼 代碼如下:
<style type="text/css">
* {
margin: 0px;
padding: 0px;
font-family: "micsoft yahei","微軟雅黑";
font-size: 15px;
}
div{
width: 50px;
height: 50px;
background: #f00;
border-radius:5px ;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
cursor: pointer;
position: absolute;
top: 60px;
left: 30px;
}
input{
position: absolute;
top: 10px;
left: 10px;
padding: 3px;
cursor: pointer;
}
</style>
html代碼
復制代碼 代碼如下:
<body>
<input type="button" value="原路返回"/>
<div></div>
</body>
javascript代碼
復制代碼 代碼如下:
<script type="text/javascript">
//1、以鼠標在div上點擊觸發(fā)為開始
//2、點擊鼠標移動時觸發(fā)鼠標移動事件 向數(shù)組內(nèi)注入數(shù)據(jù)(移動的坐標)
//3、以鼠標從div上移開為結(jié)束
//4、點擊“原路返回”按鈕遍歷數(shù)組(移動的坐標) 定時觸發(fā)數(shù)組內(nèi)的坐標移動div 達到”返回“的功能
window.onload=function(){
var oDiv=document.getElementsByTagName("div")[0];
var oBtn=document.getElementsByTagName("input")[0];
var time=null,arrTop=[],arrLeft=[];
oDiv.onmousedown=function(ev){
var event=ev || window.event;
//獲取鼠標在div內(nèi)的坐標
var disX=event.clientX-oDiv.offsetLeft;
var disY=event.clientY-oDiv.offsetTop;
arrTop=[60];
arrLeft=[30];
document.onmousemove=function(ev){
var event=ev || window.event;
//獲取拖拽后鼠標的位置
var l=event.clientX;
var t=event.clientY;
//把拖拽后的位置存進數(shù)組里面,用拖拽后鼠標的位置減去鼠標在物體上的位置,就是拖拽后物體的位置
arrLeft.push(l-disX);
arrTop.push(t-disY);
oDiv.style.left=l-disX +"px";
oDiv.style.top=t-disY +"px";
};
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
return false;
}
//原路返回的核心就是把移動時的坐標記錄下來,然后進行數(shù)組重排,并設定定時器把數(shù)組內(nèi)的搞寬賦值給物體。
oBtn.onclick=function(){
arrTop.reverse();//重排
arrLeft.reverse();//重排
var i=0;
oBtn.time=setInterval(function(){
oDiv.style.top=arrTop[i]+"px";
oDiv.style.left=arrLeft[i]+"px";
i++;
if(i==arrTop.length){
clearInterval(oBtn.time);
arrTop=[];
arrLeft=[];
}
},20);
}
}
</script>
相關文章
js對象內(nèi)部訪問this修飾的成員函數(shù)示例
這篇文章主要介紹了js對象內(nèi)部訪問this修飾的成員函數(shù)示例,需要的朋友可以參考下2014-04-04
JavaScript arguments 多參傳值函數(shù)
在一個函數(shù)體內(nèi),標識符arguments引用了arguments對象的一個特殊屬性??梢园凑諗?shù)目(而不是名字)獲取傳遞給函數(shù)的參數(shù)值。2010-10-10
getElementById().innerHTML與getElementById().value的區(qū)別
這篇文章主要介紹了getElementById().innerHTML與getElementById().value的區(qū)別,因為經(jīng)常有新手朋友問到,特整理一下,需要的朋友可以參考下2016-10-10

