JS 滑鼠事件練習—拖拽效果

來源:互聯網
上載者:User

標籤:

拖拽效果

 

HTML

<!DOCTYPE html><html>    <head>        <meta charset="utf-8">        <title>拖拽效果</title>        <link rel="stylesheet" type="text/css" href="拖拽效果.css">    </head>    <body>        <div id="box">            <h1 id="heading">點擊拖拽</h1>        </div>        <script src="拖拽效果.js"></script>    </body></html>

 

CSS

#box {    width:300px;    height:300px;    background-color:red;    padding:10px;    border:5px solid green;    text-align: center;    position:absolute;    top:50px;    left:50px;}#heading {    background-color: blue;}

 

JavaScript

//頁面載入完畢之後調用drag函數window.onload = drag;//封裝drag函數function drag() {    //擷取heading元素    var heading = document.getElementById("heading");    //滑鼠在heading元素地區按下時執行fnDown函數    heading.onmousedown = fnDown;    //滑鼠在頁面中鬆開時取消拖拽效果    document.onmouseup = function() {        document.onmousemove = null;    };};//封裝fnDown函數function fnDown(event) {    event = event || window.event;    var box = document.getElementById("box"),        heading = document.getElementById("heading"),        //取得滑鼠點擊的那個點與box左上方的距離        disY = event.clientY - box.offsetTop,        disX = event.clientX - box.offsetLeft;    //滑鼠在頁面中移動時執行匿名函數    document.onmousemove = function(event) {        event = event || window.event;        //核心思想是:滑鼠在哪兒,box跟到哪兒        //計算box距離頁面左上方的距離        var t = event.clientY - disY,            l = event.clientX - disX,            window_width = document.documentElement.clientWidth || document.body.clientWidth,            window_height = document.documentElement.clientHeight || document.body.clientHeight,            max_t = window_height - box.offsetHeight,            max_l = window_width - box.offsetWidth;        //控制box移動的最大最小距離        if(t < 0) {            t = 0;        } else if(t > max_t) {            t = max_t;        };        if(l < 0) {            l = 0;        } else if(l > max_l) {            l = max_l;        };        //box的位置跟隨滑鼠游標        box.style.top = t + "px";        box.style.left = l + "px";    };};

 

JS 滑鼠事件練習—拖拽效果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.