前端开发原生js实现鼠标拖拽

麦子学院 web前端开发视频|做后台开发需要写前端么|软件开发是前端还是后端

代码片段 1

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
    <title></title>
    <script type=”text/javascript”>
        var mouseX, mouseY;
        var objX, objY;
        var isDowm = false; //是否按下鼠标
        function mouseDown(obj, e) {
            obj.style.cursor = “move”;
            objX = div1.style.left;
            objY = div1.style.top;
            mouseX = e.clientX;
            mouseY = e.clientY;
            isDowm = true;
        }
        function mouseMove(e) {
            var div = document.getElementById(“div1”);
            var x = e.clientX;
            var y = e.clientY;
            if (isDowm) {
                div.style.left = parseInt(objX) + parseInt(x) – parseInt(mouseX) + “px”;
                div.style.top = parseInt(objY) + parseInt(y) – parseInt(mouseY) + “px”;
                document.getElementById(“span1”).innerHTML = “x:” + div.style.top + ” ” + “y:” + div.style.left;
            }
        }
        function mouseUp(e) {
            if (isDowm) {
                var x = e.clientX;
                var y = e.clientY;
                var div = document.getElementById(“div1”);
                div.style.left = (parseInt(x) – parseInt(mouseX) + parseInt(objX)) + “px”;
                div.style.top = (parseInt(y) – parseInt(mouseY) + parseInt(objY)) + “px”;
                document.getElementById(“span2”).innerHTML = “x:” + div.style.top + ” ” + “y:” + div.style.left;
                mouseX = x;
                rewmouseY = y;
                div1.style.cursor = “default”;
                isDowm = false;
            }
        }
    </script>
</head>
<body>
    <span id=”span1″></span>
    </br>
    <span id=”span2″></span>
    </br>
    <div id=”div1″ style=”background-color: Green; border: 1px solid red; height: 300px;
top: 100px; left: 100px; width: 300px; position: absolute;” onmousedown=”mouseDown(this,event)” onmousemove=”mouseMove(event)”
     onmouseup=”mouseUp(event)”>
    </div>
</body>
</html>

前端开发 电话面试|网络前端开发需要教材|bs软件开发 前端

» 本文来自:前端开发者 » 《前端开发原生js实现鼠标拖拽》
» 本文链接地址:https://www.rokub.com/5068.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!