js初學者的div移動

來源:互聯網
上載者:User

標籤:

<!DOCTYPE HTML><html lang="en-US"><head><meta charset="UTF-8"><meta name="keywords" content="div移動"><title>div移動</title></head><body>    <div id="div" style="width:200px; position:absolute; height:200px; background-color:#F90; "></div><!-- 做一個div   0.0 --></body></html><script type="text/javascript">var div = document.getElementById(‘div‘);document.onmousedown = function(e)//滑鼠點擊事件{e = e || window.event;var tops = document.getElementById(‘div‘).offsetTop;//div四個角的座標(200可變動)var lefts = document.getElementById(‘div‘).offsetLeft;var rights = lefts+200;var bottoms = tops+200;var mousex = e.pageX || e.clientX;//點擊時的滑鼠位置var mousey = e.pagey || e.clientY;var topz = document.getElementById(‘div‘).getBoundingClientRect().top;//擷取div的左上位置var leftz = document.getElementById(‘div‘).getBoundingClientRect().left;if((mousex > lefts && mousex < rights)&&(mousey > tops && mousey < bottoms)){//判斷滑鼠點擊時是否在div中document.onmousemove = function(e)//滑鼠滑動事件{var mousexx = e.pageX || e.clientX;//擷取即時滑鼠位置var mouseyy = e.pagey || e.clientY;var xx = mousexx - mousex;//求移動的距離var yy = mouseyy - mousey;leftzz = leftz + xx;topzz = topz + yy;div.style.left = leftzz +"px";//對div的左上方進行計算,與滑鼠移動的距離相同div.style.top = topzz +"px";}}}document.onmouseup = function(){//滑鼠抬起將滑動事件解除document.onmousemove = null;}</script>

  

js初學者的div移動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.