javascript - 纯javascript : Set border for draggable elements

标签 javascript html

你好,

学习 Javascript 并尝试在容器内制作可拖动元素。

如何设置可拖动边框,使元素无法移出边框? 现在我有一个问题,当你将一些东西拖到底部或右边界时,元素会移动到容器之外。 fiddle

我的 HTML 看起来像这样:

<div id="container">
    <div id="comboCon1"></div>
    <div id="comboCon2"></div>
</div>

这是我获取所有位置并调用 onmousemove 事件的函数:

function OnMouseClickDown(event) {

    var target; // -> Element that triggered the event

    if (event.target != null) { // -> If Browser is IE than use 'srcElement'

        target = event.target;
    } else {
        target = event.srcElement;
    }

    //  Check which button was clicked and if element has class 'draggable'
    if ((event.button == 1 || event.button == 0) && target.className == "draggable") {

        // Current Mouse position
        startX = event.clientX;
        startY = event.clientY;

        // Current Element position
        offsetX = ExtractNumber(target.style.left); // -> Convert to INT
        offsetY = ExtractNumber(target.style.top);

        // Border ( Div Container ) 

        minBoundX = target.parentNode.offsetLeft; // Minimal -> Top Position.
        minBoundY = target.parentNode.offsetTop;

        maxBoundX = minBoundX + target.parentNode.offsetWidth - target.offsetWidth; // Maximal.
        maxBoundY = minBoundY + target.parentNode.offsetHeight - target.offsetHeight;



        oldZIndex = target.style.zIndex;
        target.style.zIndex = 10; // -> Move element infront of others

        dragElement = target; // -> Pass to onMouseMove

        document.onmousemove = OnMouseMove; // -> Begin drag.

        document.body.focus() // -> Cancel selections

        document.onselectstart = function () { return false }; // -> Cancel selection in IE.
    }
}

这里是 onmousemove 事件:

function OnMouseMove(event) {

   dragElement.style.left = Math.max(minBoundX, Math.min(offsetX + event.clientX - startX, maxBoundX)) + "px";
   dragElement.style.top = Math.max(minBoundY, Math.min(offsetY + event.clientY - startY, maxBoundY)) + "px";
}

最佳答案

为了解决这个问题,css 有一点变化,因为你使用的是“相对”位置,容器的偏移量被赋予了 child 被拖动 所以在我的demo将拖动元素放在绝对位置,并为 clientWidth 更改 offsetWidth 并且似乎有效(水平):

// Draggable Div 1
    document.getElementById("comboCon1").style.position = "relative"; // -> Add position relative
    document.getElementById("comboCon1").style.width = "151px";
    document.getElementById("comboCon1").style.height = "10px";
    document.getElementById("comboCon1").setAttribute("class", "draggable");

    document.getElementById("comboCon1").style.border = "1px solid black";
    document.getElementById("comboCon1").style.padding = "0px";


    // Draggable Div 2
    document.getElementById("comboCon2").style.position = "relative";
    document.getElementById("comboCon2").style.width = "151px";
    document.getElementById("comboCon2").setAttribute("class", "draggable");

    document.getElementById("comboCon2").style.border = "1px solid black";
    document.getElementById("comboCon2").style.padding = "10px";


    // Container
    document.getElementById("container").style.border = "1px solid black"; 
    document.getElementById("container").style.width = "500px";
    document.getElementById("container").style.height = "500px";

    //////////////////////
    // Begin Drag events
    //////////////////////

    var startX = 0; //-> Mouse position.
    var startY = 0;

    var offsetX = 0; // -> Element position
    var offsetY = 0;

    var minBoundX = 0; // -> Top Drag Position ( Minimum )
    var minBoundY = 0;

    var maxBoundX = 0; // -> Bottom Drag Position ( Maximum )
    var maxBoundY = 0;

    var dragElement; // -> Pass the target to OnMouseMove Event

    var oldZIndex = 0; // -> Increase Z-Index while drag

    // 1)
    initDragDrop(); // -> initialize 2 Events.

    function initDragDrop() {
        document.onmousedown = OnMouseClickDown;
        document.onmouseup = OnMouseClickUp;
    }

    // 2) Click on Element
    function OnMouseClickDown(event) {

        var target; // -> Element that triggered the event

        if (event.target != null) { // -> If Browser is IE than use 'srcElement'

            target = event.target;
        } else {
            target = event.srcElement;
        }

        //  Check which button was clicked and if element has class 'draggable'
        if ((event.button == 1 || event.button == 0) && target.className == "draggable") {

            // Current Mouse position
            startX = event.clientX;
            startY = event.clientY;

            // Current Element position
            offsetX = ExtractNumber(target.style.left); // -> Convert to INT

            offsetY = ExtractNumber(target.style.top);

            // Border ( Div Container ) 

            minBoundX = target.parentNode.offsetLeft; // Minimal -> Top Position.
            console.log(target.parentNode.getBoundingClientRect(), target)
            minBoundY = target.parentNode.offsetTop;

            maxBoundX = minBoundX + target.parentNode.clientWidth - target.clientWidth; // Maximal.
            console.log(maxBoundX, target.parentNode.clientWidth, target.clientWidth);
            maxBoundY = minBoundY + target.parentNode.offsetHeight - target.offsetHeight;



            oldZIndex = target.style.zIndex;
            target.style.zIndex = 10; // -> Move element infront of others
            target.style.position = 'absolute'

            dragElement = target; // -> Pass to onMouseMove

            document.onmousemove = OnMouseMove; // -> Begin drag.

            document.body.focus() // -> Cancel selections

            document.onselectstart = function () { return false }; // -> Cancel selection in IE.
        }
    }

    // 3) Convert current Element position in INT
    function ExtractNumber(value) {

        var number = parseInt(value);

        if (number == null || isNaN(number)) {
            return 0;
        }
        else {
            return number;
        }
    }

    // 4) Drag
    function OnMouseMove(event) {

       dragElement.style.left = Math.max(minBoundX, Math.min(offsetX + event.clientX - startX, maxBoundX)) + "px";

       dragElement.style.top = Math.max(minBoundY, Math.min(offsetY + event.clientY - startY, maxBoundY)) + "px";
    }

    // 5) Drop
    function OnMouseClickUp(event) {
        if (dragElement != null) {

            dragElement.style.zIndex = oldZIndex; // -> set Z-index 0.

            document.onmousemove = null;
            document.onselectstart = null;

            dragElement = null; // -> No more element to drag.
        }
    }

关于javascript - 纯javascript : Set border for draggable elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46771610/

相关文章:

php - DOMDocument saveHTML 错误地编码 href 属性

用于移动应用程序的 PHP websocket

javascript - 在同一页面通过 Javascript 函数加载 Applet

javascript - 使用外部 Node 脚本连接到已在index.js中定义的socket-io

javascript - 使用项目依赖项的输入定义 Gradle 任务?

javascript - 一页上多个div悬停效果

javascript - 将全局样式应用于选定的类

javascript - 在通过 JavaScript 连接的链接上省略 HREF 是好习惯(还是好主意)?

javascript - 将背景图像水平固定为标题中的 Logo

jquery - 在 li 上添加类并在单击时添加类