jQuery drag - to get start and stop coordinates

爷,独闯天下 提交于 2019-12-24 17:17:07

问题


Hi I have been looking at jQuery's drag library for a method whereby if I hold the mouse button and drag the mouse, then release the button, I get the start and end coordinates of that drag, based on raw screen pixels. I have drawn a blank on that, and haven't found anything on StackOverlaod either.

Can anyone recommend an example?

Thanks Graham


回答1:


You can use get the events of dragstart and dragend. Try this code

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/jquery-wp-content/themes/jquery/css/base.css?v=1">
<style>
    #myDiv
    {
        width: 20px;
        height: 20px;
        background-color: Red;
    }
</style>
<script>
    $(document).ready(function () {
        $("#myDiv").draggable({
            start: function (e, ui) {
                var parentOffset = $(this).parent().offset();
                var relX = e.pageX - parentOffset.left;
                var relY = e.pageY - parentOffset.top;
                $("#start").html(" x: " + relX + ", y: " + relY);
            },
            stop: function (e, ui) {
                var parentOffset = $(this).parent().offset();
                var relX = e.pageX - parentOffset.left;
                var relY = e.pageY - parentOffset.top;
                $("#end").html(" x: " + relX + ", y: " + relY);
            }

        });
    });

</script>
</head>
<body>
start Position:<span id="start"></span>
<br />
End Position:<span id="end"></span>
<div id="myDiv">
</div>

</body>
</html>

Edited If you want to get the mouse position without a drag element, use like this

<script>
    $(document).ready(function () {
        $("body").mousedown(function (e) {
            var parentOffset = $(this).parent().offset();
            var relX = e.pageX - parentOffset.left;
            var relY = e.pageY - parentOffset.top;
            $("#start").html(" x: " + relX + ", y: " + relY);
        });

        $("body").mouseup(function (e) {
            var parentOffset = $(this).parent().offset();
            var relX = e.pageX - parentOffset.left;
            var relY = e.pageY - parentOffset.top;
            $("#end").html(" x: " + relX + ", y: " + relY);
        });

    });
</script>


来源:https://stackoverflow.com/questions/21431879/jquery-drag-to-get-start-and-stop-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!