如何创建可拖动的菜单div(桌面和移动)

时间:2013-01-06 22:04:35

标签: javascript jquery

enter image description here

如何制作以上内容? 它可以通过拖动菜单文本区域(菜单图像或一些内部div)来上下拖动,并且当拖动时div会向下或向上(具有最大和最小限制)。

我无法使这段代码正常工作,任何人都可以提供实用的代码吗?

whole_menu.onPress = function() {
startDrag(this);
};
whole_menu.onRelease =function () {
stopDrag();
};


whole_menu.onPress = function() {
startDrag(this, false, 0, this._y, 800-this._width, this._y);
};
whole_menu.onRelease =function () {
stopDrag();
};

修改 添加了更多解释和代码,所以
无需关闭此问题

1 个答案:

答案 0 :(得分:5)

没有jQuery UI )我构建它,应该适用于所有移动设备! (也在手机上测试过 - Android)

jsBin demo

var $MB = $('#menu_btn'),
    $M = $('#menu'),
    $DOM = $(document),
    startAtY = 10, // CSS px
    endAtY = 270,  // CSS #menu height px
    clickedAtY,
    clickEventType= document.ontouchstart !== null ? 'mousedown' : 'touchstart',
    moveEventType = document.ontouchmove  !== null ? 'mousemove' : 'touchmove' ,
    endEventType  = document.ontouchend   !== null ? 'mouseup'   : 'touchend'  ;

$MB.on(clickEventType, function( e ) { 

  e.preventDefault();  

  clickedAtY	= e.pageY - $(this).offset().top;
  if(clickEventType === 'touchstart'){
    clickedAtY = e.originalEvent.touches[0].pageY - $(this).offset().top;
  }
  
  $DOM.on(moveEventType, moveHandler)
      .on(endEventType, stopHandler);

});

function moveHandler( e ) {
  var posY = e.pageY - clickedAtY;
  if(moveEventType === 'touchmove') {
    posY = e.originalEvent.touches[0].pageY - clickedAtY;
  }
  posY = Math.min( Math.max(0, posY), endAtY - startAtY);
  $M.css({top: posY});
}

function stopHandler() {
  $DOM.off(moveEventType, moveHandler)
      .off(endEventType,  stopHandler);
}
*{margin:0;padding:0;}

body{font-family:Arial;}

#menu_wrapper{
  height:0px;
}
#menu{
  background:#444;
  height:280px;
  margin-top:-270px;
  color:#ccc;
  position:relative;
}
#menu_btn{
  cursor:pointer;
  background:#444;
  padding:10px 20px;
  position:absolute;
  bottom:-30px;
    left:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="menu_wrapper">
  <div id="menu">

    <div id="menu_btn">DRAG ME DOWN</div>
  </div>
</div>