添加滑动功能可隐藏HTML菜单

时间:2017-03-20 13:21:44

标签: javascript jquery css

我有使用CSS构建的菜单,当用户触摸时,菜单滑出,当他触摸背景时,它再次在移动设备上滑动。

问题在于我想让菜单在移动应用菜单中工作,而不是触摸要滑入的背景,我希望用户能够滑动并隐藏菜单

小提琴:https://jsfiddle.net/livewirerules/ek4tkrc0/2/

以下是css

nav ul li { line-height: 50px; }

#nav {
    padding: 20px;
    text-align: left;
    position: fixed;
    height: 100%;
    top: 0;
    width: 60%;
    max-width: 275px;
    background: rgb(255, 219, 58);
    box-shadow: -3px 0 10px rgba(0,0,0,0.2);
    overflow-y: auto;
    z-index: 99;
}

#nav:not(:target) {
    left: -100%;
    transition: left .5s;
}

#nav:target {
    left: 0;
    transition: left .25s;
}

#nav:target + #nav_modal { display: block; }

#nav_modal {
    display: none;
    position: fixed;
    top: 0;
    right: 0;
    height: 100%;
    width: 100%;
    background-color: rgba(0,0,0,.8);
    overflow: hidden;
    z-index: 9;
} 

的JavaScript

function initialHash() {
  'use strict';
  window.location.href = "#";
}

document.getElementById('nav_modal').addEventListener('click', initialHash, false);

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您可以在#nav上使用touchstart,touchmove,touchend事件。这是一个例子

function initialHash() {
  'use strict';
  window.location.href = "#";
}

function handleTouch(e) {
    var x = e.changedTouches[0].clientX;
  var total = this.clientWidth;
  var position = x - total;
  if ( position < 0 ) this.style.left = (x-total) + 'px'
  else if (position >= 0) this.style.left = 0 + 'px'
}
function handleTouchEnd(e) {
    var x = e.changedTouches[0].clientX;
  var total = this.clientWidth;
  var position = x - total;
  this.style.left = "";
  if ( position <= -total*0.5 ) initialHash();
}
document.querySelector('#nav').addEventListener('touchstart', handleTouch, false)
document.querySelector('#nav').addEventListener('touchmove', handleTouch, false)
document.querySelector('#nav').addEventListener('touchend', handleTouchEnd, false)
document.getElementById('nav_modal').addEventListener('click', initialHash, false);

工作示例:https://jsfiddle.net/cnexans/Ln60t4h6/1/