Как предотвратить щелчок, когда div находится в перетаскиваемом состоянии и в теле - PullRequest
0 голосов
/ 12 февраля 2020

У меня есть сценарий, где я должен скрывать и показывать div по нажатию перетаскиваемого div. Мне нужно предотвратить функцию onclick, пока div находится в состоянии перетаскивания. Мне нужно предотвратить этот отвратительный div внутри тела.

    //Make the DIV element draggagle:
    
    
    
    var new_html = '<span class="caps">Moshi</span>';
    var new_elem = document.createElement('div');
    new_elem.innerHTML ='<div id="mydiv">   <div id="mydivheader">Move me</div>    </div>';
    document.querySelector('body').appendChild(new_elem);
    
    dragElement(document.getElementById("mydiv"));
    document.getElementById("mydiv").addEventListener("click", function(){
      alert('click')
    });
    function dragElement(elmnt) {
      var pos1 = 10, pos2 = 10, pos3 = 10, pos4 = 10;
      if (document.getElementById(elmnt.id + "header")) {
        /* if present, the header is where you move the DIV from:*/
        document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
      } else {
        /* otherwise, move the DIV from anywhere inside the DIV:*/
        elmnt.onmousedown = dragMouseDown;
      }
    
      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }
    
      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        // set the element's new position:
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
      }
    
      function closeDragElement() {
        /* stop moving when mouse button is released:*/
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
    #mydiv {
      position: absolute;
      z-index: 9;
      background-color: #f1f1f1;
      text-align: center;
      border: 1px solid #d3d3d3;
    }
    
    #mydivheader {
    height:40px;
      padding: 10px;
      cursor: move;
      z-index: 10;
      background-color: #2196F3;
      color: #fff;
    }
    <!DOCTYPE html>
    <html>
    <style>

    </style>
    <body>

    </body>
    </html>

PS: Я хочу добиться этого с помощью чистой javascript манипуляции с DOM. Пожалуйста, предложите, как это исправить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...