문제

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

도움이 되었습니까?

해결책

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top