简体   繁体   中英

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.

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.

Here's the fiddle: 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.

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

with 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

It can be super simple with getElementsBtClassName :

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

and inside drop handler you just check 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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