Use the child to drag the parent

I want to do something like a navigation bar that can move an entire element without allowing it to drag anywhere on the parent whole element to control drag and drop. For instance:

<div class="undraggable">
    <div class="draggable"></div>
    content
</div>

Dragging along the title bar drags the entire window in which it is contained inside, but dragging it to another location in the container window does not drag the window.

I tried using dragresize , but I can’t only make a dragged object (I don’t want to resize) with its code.

+5
source share
3 answers
  • Register the mousedown handler on the drag controller (for example, in the window title bar).
  • (, ).

:
http://phrogz.net/js/PhrogzWerkz/WerkWin.html

, , jQuery, , , , .

: http://jsfiddle.net/VCQuN/1/

<div class="window">
  <div class="titlebar">Hello, World!</div>
  <div class="content">
    <p>Window <b>Content!</b></p>
  </div>
</div>
// For each item with a `window` class…
var windows = document.querySelectorAll('.window');
[].forEach.call(windows,function(win){

  // …find the title bar inside it and do something onmousedown
  var title = win.querySelector('.titlebar');
  title.addEventListener('mousedown',function(evt){

    // Record where the window started
    var real = window.getComputedStyle(win),
        winX = parseFloat(real.left),
        winY = parseFloat(real.top);

    // Record where the mouse started
    var mX = evt.clientX,
        mY = evt.clientY;

    // When moving anywhere on the page, drag the window
    // …until the mouse button comes up
    document.body.addEventListener('mousemove',drag,false);
    document.body.addEventListener('mouseup',function(){
      document.body.removeEventListener('mousemove',drag,false);
    },false);

    // Every time the mouse moves, we do the following 
    function drag(evt){
      // Add difference between where the mouse is now
      // versus where it was last to the original positions
      win.style.left = winX + evt.clientX-mX + 'px';
      win.style.top  = winY + evt.clientY-mY + 'px';
    };
  },false);
});
+3

- , jquery ui - , , , JQUERY UI, , . : http://jsfiddle.net/VPMFs/

<style>
.undraggable{height:500px;width:500px;background:blue;}
.draggable{height:100px;width:100px;background:white;}
</style>
<div class="undraggable">
<div class="draggable">drag me!</div>
</div>

<script>
$('.undraggable').draggable({handle: '.draggable'});
</script>
+6

jQuery UI draggable:

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

jQuery, (draggable ): http://jqueryui.com/download.

It has many configuration options - your wording is a bit ambiguous, but I think you might need a handle option: http://jqueryui.com/demos/draggable/#handle

0
source

All Articles