absolute和relative定位簡單示例&div在屏幕拖動

<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>absolute和relative定位示例</title>
    <script src="jquery-1.8.3.min.js"></script>
    <style type="text/css">
        .divFather{
            left: 200px;
            top: 200px; 
            position: absolute;/* 絕對定位 */
            height: 300px;
            width: 300px;
            background: #bfb0b0;
            display: flex;/* 設置爲彈性佈局 */
            justify-content: space-around;/* 內容左右居中顯示 */
            align-items: center; /* 內容上下居中顯示 */
            z-index: 1;
        }
        .divSon{
            position: relative;/* 絕對定位 */
            height: 150px;
            width: 150px;
            background: #ca7979;
            display: flex;
            justify-content: space-around;
            align-items: center;
        }
        .divGrandson{
            height: 60px;
            width: 60px;
            position: absolute;/* 絕對定位 */
            background: green;
        }
        .moveDiv{
            position: absolute;
            left: 100px;
            top: 50px;
            width: 150px;
            height: 150px;
            background: #d4bfbf;
            display: flex;
            justify-content: space-around;
            align-items: center;
            border-radius: 100px;
            z-index:2;
        }
    </style>
</head>
<body>
    <div class="divFather">
        <div class="divSon">
            <div class="divGrandson">
            </div>
        </div>
    </div>
    <div class="moveDiv">
        我是鼠標拖動模塊
    </div>
    <script type="text/javascript">
      // 獲取屏幕的高寬度
      let cw = $(window).width();
      let ch = $(window).height();
      // 鼠標按下時獲取鼠標在屏幕的位置
      $(".moveDiv").mousedown(function(e){
         e = e || window.event;
         // 獲取鼠標在元素上的位置(鼠標按下時在元素上得位置)
         let X = e.clientX - $(".moveDiv").offset().left;
         let Y = e.clientY  - $(".moveDiv").offset().top;

         $(".moveDiv").mousemove(function(e){
             console.log(cw ,ch);
             e = e || window.event;
             let x = e.clientX - X;
             let y = e.clientY - Y;
             if(x<0)x=0;
             if(y<0)y=0;
             if(x + $('.moveDiv').width() > cw)  x = cw-$('.moveDiv').width();
             if(y +$('.moveDiv').height() > ch)  y = ch-$('.moveDiv').height();
             $('.moveDiv').css({
                 'left':x,
                 'top':y
             })
         })
      });
      // 鼠標擡起事件
      $(document).mouseup(function(){
         $(".moveDiv").unbind("mousemove")
      })
    </script> 
</body>
</html>

實際展示效果圖:

html代碼可以直接複製出去,創建一個demo.html,然後找到jquery引入即可,訪問頁面可以展示以上效果。

或者直接在本人百度網盤下載即可

鏈接: https://pan.baidu.com/s/1c5Uy7VbK1PaLIgW8-RvapA 提取碼: 3swy

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章