zoukankan      html  css  js  c++  java
  • 【JS】原生实现拖拽

    <!DOCTYPE html>
    <html lang="en">
        <head>    
            <meta charset="UTF-8">    
            <meta name="viewport" content="width=device-width, initial-scale=1.0">    
            <title>Document</title>
        </head>
        <body>    
            <!-- <img id="ball" src="https://js.cx/clipart/ball.svg" width = "100px" height = "100px" alt="">
            <object data="https://js.cx/clipart/ball.svg" width="100" height="100" type="image/svg+xml" codebase="http://www.adobe.com/svg/viewer/imstall/" /> -->
            <img id="ball" src = "https://www.baidu.com/img/bd_logo1.png?qua=high&where=super" alt = "logo">    
            <div>helloworld</div>
            <script>       
                const ball=document.querySelector("#ball")       
                ball.onmousedown = function(event) {       
                    let shiftX = event.clientX - ball.getBoundingClientRect().left;       
                    let shiftY = event.clientY - ball.getBoundingClientRect().top;        
                    ball.style.position = 'absolute';        
                    ball.style.zIndex = 1000;        
                    document.body.append(ball);        
                    moveAt(event.pageX, event.pageY);        
                    // 移动现在位于坐标 (pageX, pageY) 上的球        
                    // 将初始的偏移考虑在内        
                    function moveAt(pageX, pageY) {        
                        ball.style.left = pageX - shiftX + 'px';        
                        ball.style.top = pageY - shiftY + 'px';        
                    }        
                    function onMouseMove(event) {        
                        moveAt(event.pageX, event.pageY);        
                    }        
                    // 在 mousemove 事件上移动球        
                    document.addEventListener('mousemove', onMouseMove);        
                    // 放下球,并移除不需要的处理程序        
                    ball.onmouseup = function() {        
                        document.removeEventListener('mousemove', onMouseMove);        
                        ball.onmouseup = null;        
                        };        
                    };        
                    ball.ondragstart = function() {        
                        return false;    
                    };    
            </script>
        </body>
    </html>
    
  • 相关阅读:
    I Think I Need a Houseboat
    iOS 8 模糊视图(毛玻璃效果)的简单实现UIVisualEffectView
    freemarker报错之二
    [算法]有趣算法合辑[31-40]
    计算机专业术语全称及含义整理
    JAVA经常使用数据结构及原理分析
    我读经典(6):读《文明之光》有感
    流水号的生成(日期+业务码+自增序列)
    桶排序算法
    3.5星|《哈佛商学院最受欢迎的营销课》:跳出营销红海:逆向战略、超越行业和敌意品牌
  • 原文地址:https://www.cnblogs.com/kinologic/p/15093246.html
Copyright © 2011-2022 走看看