How do I prevent drag on a child, but allow drag on the parent?

前端 未结 6 1067
情深已故
情深已故 2020-12-07 00:33

I have a div which the user can drag, inside that div is a span with some text which I want to allow the user to select (thus they cannot drag it). How do I allow the div to

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 01:19

    I was inspired by a few of the answers here and I think I came up with the cleanest and most reusable solution. I use a mouse down event to check if the element should be draggable or not. I do this by verifying if it has a specific class name that I only assign to draggable elements. On the mouse up event, I go through all of the elements with that class tag and set their draggable values back to true.

    This can break if the input node is a deep child of the draggable div, but then you can use the same algorithm as in the mouse up event and set all of the values to false.

    document.addEventListener('mousedown', function (event) {
    	var clickedElem = event.target;
        if(!clickedElem.classList.contains("drop_content")){
            clickedElem.parentElement.setAttribute("draggable",false);
        }
    }, false);
    
    document.addEventListener('mouseup', function () {
        var boxes = document.querySelectorAll(".drop_content");
        for(var i = 0; i < boxes.length; i++){
            boxes[i].setAttribute("draggable",true);
        }
    }, false);
    div{
      display:block;
      background: black;
      padding: 5px;
      margin: 2px;
    }
    
      
        

提交回复
热议问题