简体   繁体   English

是否可以限制div可以拥有的最大孩子数量?

[英]Is it possible to limit the maximum number of children a div can have?

So I want to limit the number of children a div can have. 所以我想限制div可以拥有的孩子数量。

The idea is that you have a selected commands div where you can drag and drop whichever commands (essentially buttons) are available to you at any given time, from another div called available commands , but only up to a maximum of four at a time. 这个想法是你有一个selected commands div ,你可以在任何给定的时间拖放任何命令(基本上是按钮),从另一个div称为available commands ,但一次最多只能拖动四个available commands

Here's the fiddle: http://jsfiddle.net/v9Fg8/2/ 这是小提琴: http//jsfiddle.net/v9Fg8/2/

How can I limit the number of maximum possible children this div can have, so that when it reaches 4, one of the children gets replaced on the drop event. 如何限制此div可能具有的最大子项数,以便当它达到4时,其中一个子项将在drop事件中被替换。

You could check if the container has too many elements and save the parent element when dragging like this 您可以检查容器是否包含太多元素,并在拖动时保存父元素

function drag(ev) {
    itemParent = ev.target.parentElement;
    //console.log(itemParent);
    ev.dataTransfer.setData("Text", ev.target.id);
};

function drop(ev) {
    ev.preventDefault();
    if (ev.target.childNodes.length == 4) {
        var data = ev.dataTransfer.getData("text");
        console.log(itemParent);
        itemParent.appendChild(document.getElementById(data));
    } else {
        var data = ev.dataTransfer.getData("Text");
        ev.target.appendChild(document.getElementById(data));
    }
};

DEMO DEMO

with jQuery 用jQuery

function drop(ev) {
    ev.preventDefault();
    if ($('.commands').not(itemParent).children().length == 4) {
        var data = ev.dataTransfer.getData("text");
        console.log(itemParent);
        itemParent.appendChild(document.getElementById(data));
    } else {
        var data = ev.dataTransfer.getData("Text");
        $('.commands').not(itemParent).append($('#' + data));
        //ev.target.appendChild(document.getElementById(data));
    }
};

This code is better, so you can drop the elements on elements so you don't append to the boxes. 此代码更好,因此您可以删除元素上的元素,这样就不会附加到框中。

DEMO DEMO

It can be super simple with getElementsBtClassName : 使用getElementsBtClassName可以非常简单:

var dropped = document.getElementById('selected').getElementsByClassName('button');

and inside drop handler you just check dropped.length : 和内部drop处理程序,你只需检查dropped.length

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));

    // Check number of children
    if (dropped.length > 4) {
        ev.target.removeChild(dropped[0]);
    }
};

Demo: http://jsfiddle.net/v9Fg8/6/ 演示: http//jsfiddle.net/v9Fg8/6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM