0

通常我更喜欢为琐碎的问题编写自己的解决方案,因为通常插件会添加许多不需要的功能并增加您的项目规模。大小使页面变慢,并且 100k 页面浏览量/天网站中的 30k 差异(与 jquery 可拖动相比)对账单产生了很大影响。我已经使用 jquery,我认为这就是我现在所需要的,所以请不要告诉我使用另一个插件或框架来拖动东西。

考虑到这一点,我编写了以下代码,以允许可以拖动一个框。代码工作得很好(任何关于代码本身的提示都会非常感谢),但是当我将鼠标光标拖动到框限制的左侧时出现了一个小故障:框内的文本被选中。

我该如何解决?谢谢。

JavaScript:

$(document).ready(function () {

    var x = 0;
    var y = 0;

    $("#d").live("mousedown", function () {

        var element = $(this);
        var parent = element.parent();

        $(document).mousemove(function (e) {

            var x_movement = 0;
            var y_movement = 0;

            if (x == e.pageX || x == 0) {
                x = e.pageX;
            } else {
                x_movement = e.pageX - x;
                x = e.pageX;
            }

            if (y == e.pageY || y == 0) {
                y = e.pageY;
            } else {
                y_movement = e.pageY - y;
                y = e.pageY;
            }

            var left = parseFloat(element.css("left")) + x_movement;

            // hold inside left
            if (left <= 0) left = 0;

            // hold inside right
            var max_right = (parseFloat(element.outerWidth()) - parent.width()) * -1;
            if (left >= max_right) left = max_right;

            element.css("left", left);

            var top = parseFloat(element.css("top")) + y_movement;

            // hold inside top
            if (top <= 0) top = 0;

            // hold inside bottom
            var max_bottom = (parseFloat(element.outerHeight()) - parent.height()) * -1;
            if (top >= max_bottom) top = max_bottom;

            element.css("top", top);

            return false;

        });

    });

    $(document).mouseup(function () {
        x = 0;
        y = 0;
        $(document).unbind("mousemove");
    });

});

HTML:

<div style="position: relative; width: 500px; height: 500px; background-color: Red;">
    <div id="d" style="position: absolute; width: 100px; left: 0px; height: 100px; top: 0px; cursor: move; border: 1px solid black;">a</div>
</div>
4

2 回答 2

2

选择文本的事实与 JavaScript 无关。如果您在按下一个按钮时在鼠标光标周围移动,这是浏览器和选择文本的问题。

您可以应用一些 css,这将阻止文本被选中,至少在现代浏览器上:

#d {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

(这不是标准css,但应该可以。)

于 2012-06-12T23:37:41.490 回答
1

您可以在元素上使用 CSS 来阻止选择,以及将unselectable="on"属性添加到元素

示例:http: //jsfiddle.net/PS79Y/

CSS:

#d{
 -moz-user-select: -moz-none; 
 -khtml-user-select: none;
 -webkit-user-select: none;
 -ms-user-select: none;
 user-select: none;
}

要查看-moz-none和 just之间的示例none,请访问https://developer.mozilla.org/en/CSS/user-select

于 2012-06-12T23:37:21.163 回答