为什么不是'这个jQuery汉堡包按钮不工作

Why isn't this jQuery hamburger button working?

本文关键字:汉堡包 按钮 工作 jQuery 这个 为什么不      更新时间:2023-09-26

我修改了这里的一个教程,但很难让它正常工作。

目标是让整个页面向左滑动,以显示导航菜单。现在我只是专注于让动画发挥作用。

HTML:

<div class="pg-container">
  <div class="nav-bar">
    <h1>My Site</h1>
    <img src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/menu-alt-512.png" width="40" height="40px" class="hamburger">
  </div>
  <div class="welcome">
    <h2>Hamburger Demo</h2>
  </div>
</div>

CSS:

body {
  margin: 0;
}
h1 {
  font-family: sans-serif;
  padding: 0;
  margin: 0;
  font-size: 2em;
  float: left;
}
h2 {
  color: white;
  font-size: 3em;
  text-align: center;
}
.pg-container {
  height: 100vh;
  background-image: url(https://pixabay.com/static/uploads/photo/2013/10/02/23/03/dawn-190055_960_720.jpg);
  background-size: cover;
}
.nav-bar {
  height: 40px;
  background-color: hsla(360, 100%, 100%, 0.51)
}
.hamburger {
  float: right
}
.welcome {
  margin: 10em 0
}

和Javascript:

// Open the menu
  $(".hamburger").click(function() {
  // set width of page container
    var contentWidth = $(".pg-container").width();
    $(".pg-container").css('width', contentWidth);
  // disable all scrolling on mobile devices while menu is shown
    $(".pg-container").bind('touchmove', function(e){e.preventDefault()})
    // set margin for whole container with jQuery UI animation
    $(".pg-container").animate({"margin-right": "50%"}, 700)
})

我怀疑这个问题与设置页面宽度的部分有关,以防止添加右边距时更改布局。这是因为Javascript在添加上边距而不是右边距时有效。

它不起作用,因为您在边距之前设置了宽度。

删除此部分:

var contentWidth = $(".pg-container").width();
$(".pg-container").css('width', contentWidth);

此处的示例:https://jsfiddle.net/7oqw85ph/

全宽布局:https://jsfiddle.net/7oqw85ph/1/