jQuery draggable removing without changing positio

2019-09-10 04:36发布

问题:

I am building a page layout configuration system on jQuery. So everyone, who is using my website can make it personal by moving elements on webpage. But, I have a problem.

Every element on my page is a draggable div with option to be removed from page if necessary. When user wants to remove an element, he clicks on inner div and the following function is called:

<script language="javascript">
    $(function() {
        $('.close').click(function(){
                    $(this).parent().hide();
                });
    });
</script>
    <div class="main"><div class="close"></div></div>

When user wants to add an element on page, he clicks on link and followinf function is called:

function addNewWidget(page_name, size){
    var page = $('#'+page_name);
    var closeDiv = $(document.createElement("div")).attr("class", "close").html('X');
    closeDiv.click(function(){
        $(this).parent().hide();
    });
    var div = $(document.createElement("div"))
    div.attr("class", "drag");
    div.appendTo(page);
    closeDiv.appendTo(div);
    div.draggable({
        containment: "#page",
        scroll: false,
        grid: [200, 200]
    });
    div.css("top:0; left:0");
    div.addClass(size);
    div.addClass('widget');
}

Everything works fine, but when element is removed, other elements, which were on page are moving up. It is because of element positioning in the code. These divs in the code are before div, which was removed, and their absolute top is changed by -heghtOfRemovedElement

Is there any way to prevent other elements from moving up?

回答1:

I came across your question when I was looking for a solution for something completely different and yet with the same problem: Upon removing an element from it's container the other elements would shuffle around.

I'm not sure if the solution I eventually worked out will help you, but in case it does ... it was simply to make sure that your elements are set as position: absolute. I was using drag/drop functionality as well. Turns out that when you drop into a "droppable" zone the position:absolute attribute isn't implicitly set, so you have to do it manually.