jQuery拖动-获取开始和停止坐标 [英] jQuery drag - to get start and stop coordinates

查看:142
本文介绍了jQuery拖动-获取开始和停止坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找jQuery的拖动库,寻找一种方法,如果我按住鼠标按钮并拖动鼠标,然后松开按钮,我将基于原始屏幕像素获取该拖动的开始和结束坐标.我在上面画了一个空白,也没有在StackOverlaod上找到任何东西.

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?

谢谢 格雷厄姆

推荐答案

您可以使用get dragstart和dragend事件. 试试这个代码

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>

这篇关于jQuery拖动-获取开始和停止坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆