首页 > Web开发 > 详细

【JS】原生实现拖拽

时间:2021-08-03 15:25:24      阅读:12      评论:0      收藏:0      [点我收藏+]
<!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" >
        <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>

【JS】原生实现拖拽

原文:https://www.cnblogs.com/kinologic/p/15093246.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!