質問

これは更新および変更されたスクリプトです。ユニバーサル化する場合を除いて、完全に機能します...必要なたびにfunction(e){BOX.Draggable.elemen = e.target || e.srcElement; elementDraggable(e);を実行する必要がないように、どうすれば作成できるかを確認してください。別の要素にドラッグ可能な関数を使用しますか? ジェネラコディセタグプレ

役に立ちましたか?

解決

jQueryはあなたのオプションですか?コードがすでに存在するため、実行していることが非常に簡単になります。

http://jqueryui.com/demos/draggable/

デモ

JavaScriptコード ジェネラコディセタグプレ

他のヒント

これは、divをドラッグするための優れたno-jQueryスクリプトです: http://jsfiddle.net/g6m5t8co/1/ ジェネラコディセタグプレ

まあ、あなたの移動コードは次のように単純化されます: ジェネラコディセタグプレ

ここでの基本的な計算-e.clientXe.clientYはここの位置にまったく影響を与えないので、offsetLeftを取得して、style.leftに再割り当てするだけで、上部も同じです。したがって、動きはまったくありません。

あなたがする必要があるのは、clientXが発生したときにclientYmousedownを保存し、それに基づいて減算を行うことです。

ああ、あなたもイベントリスナーを間違って設定しています。現在のように、divMoveを1回実行すると、戻り値(ここではundefined)がリスナーとしてアタッチされた関数になります。代わりに、function(e) {divMove(dxy,e || window.event);}を使用してください。

I modified Shaedo's code a little bit, wraps it in a function and add a feature that you can drag an element by only parts of it or its children, say the title bar of a div. Note in this demo, you can only drag the red area to move the blue area.

function makeDragable(dragHandle, dragTarget) {
  let dragObj = null; //object to be moved
  let xOffset = 0; //used to prevent dragged object jumping to mouse location
  let yOffset = 0;

  document.querySelector(dragHandle).addEventListener("mousedown", startDrag, true);
  document.querySelector(dragHandle).addEventListener("touchstart", startDrag, true);

  /*sets offset parameters and starts listening for mouse-move*/
  function startDrag(e) {
    e.preventDefault();
    e.stopPropagation();
    dragObj = document.querySelector(dragTarget);
    dragObj.style.position = "absolute";
    let rect = dragObj.getBoundingClientRect();

    if (e.type=="mousedown") {
      xOffset = e.clientX - rect.left; //clientX and getBoundingClientRect() both use viewable area adjusted when scrolling aka 'viewport'
      yOffset = e.clientY - rect.top;
      window.addEventListener('mousemove', dragObject, true);
    } else if(e.type=="touchstart") {
      xOffset = e.targetTouches[0].clientX - rect.left;
      yOffset = e.targetTouches[0].clientY - rect.top;
      window.addEventListener('touchmove', dragObject, true);
    }
  }

  /*Drag object*/
  function dragObject(e) {
    e.preventDefault();
    e.stopPropagation();

    if(dragObj == null) {
      return; // if there is no object being dragged then do nothing
    } else if(e.type=="mousemove") {
      dragObj.style.left = e.clientX-xOffset +"px"; // adjust location of dragged object so doesn't jump to mouse position
      dragObj.style.top = e.clientY-yOffset +"px";
    } else if(e.type=="touchmove") {
      dragObj.style.left = e.targetTouches[0].clientX-xOffset +"px"; // adjust location of dragged object so doesn't jump to mouse position
      dragObj.style.top = e.targetTouches[0].clientY-yOffset +"px";
    }
  }

  /*End dragging*/
  document.onmouseup = function(e) {
    if (dragObj) {
      dragObj = null;
      window.removeEventListener('mousemove', dragObject, true);
      window.removeEventListener('touchmove', dragObject, true);
    }
  }
}

makeDragable('#handle', '#moveable')
#moveable {
    width: 100px;
    height: 100px;
    background: blue;
}

#handle {
    width: 50px;
    height: 50px;
    cursor: move;
    background: red;
}
<div id="moveable">
    <div id="handle">
    </div>
</div>

After trying jnoreiga's accepted answer, I found it very annoying that the dragged element abruptly snapped to the top left corner, rather than maintaining the same relative position.

This snippet prevents the awkward aforementioned behavior via an offset, and provides a simple interface to create draggable elements one at a time or en masse via a forEach call or similar.

window.onload = function() {
  draggable(document.getElementById('foo'));
}

function draggable(el) {
  el.addEventListener('mousedown', function(e) {
    var offsetX = e.clientX - parseInt(window.getComputedStyle(this).left);
    var offsetY = e.clientY - parseInt(window.getComputedStyle(this).top);
    
    function mouseMoveHandler(e) {
      el.style.top = (e.clientY - offsetY) + 'px';
      el.style.left = (e.clientX - offsetX) + 'px';
    }

    function reset() {
      window.removeEventListener('mousemove', mouseMoveHandler);
      window.removeEventListener('mouseup', reset);
    }

    window.addEventListener('mousemove', mouseMoveHandler);
    window.addEventListener('mouseup', reset);
  });
}
/* The only required styling is position: absolute */
#foo {
  position: absolute;
  border: 1px solid black;
  overflow: hidden;
}

/* Prevents inconsistent highlighting of element while being dragged
   Copied from https://stackoverflow.com/questions/826782 */
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}
<div id="foo" class="noselect">This is a draggable div!</div>

An additional method to "niente00" code.

init : function(className){
    var elements = document.getElementsByClassName(className);
    for (var i = 0; i < elements.length; i++){
        elements[i].onmousedown = function(){mydragg.startMoving(this,'container',event);};
        elements[i].onmouseup = function(){mydragg.stopMoving('container');};
        }
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top