【问题标题】:whats "wrong" with this toggle script?这个切换脚本有什么“错误”?
【发布时间】:2016-02-16 03:37:21
【问题描述】:

我使用这个 JS 代码来切换我的响应式菜单,但它在手机中运行不流畅。你知道为什么吗?

    <script>
    $(function() {
        var pull        = $('.slide-toggle');
            menu        = $('.menu');
            menuHeight  = menu.height();

        $(pull).on('click', function(e) {
            e.preventDefault();
            menu.slideToggle(500);
        });

        $(window).resize(function(){
            var w = $(window).width();
            if(w > 768 && menu.is(':hidden')) {
                menu.removeAttr('style');
            }
        });
    });
</script>

感谢您的帮助!0

【问题讨论】:

  • 使用 jquery 动画例如:slideToggle 在移动设备上通常很慢,您可以尝试查找 css3 过渡(请参阅此问题:stackoverflow.com/questions/8860631/…
  • +1 用于 CSS3 过渡建议。 slideToggle 需要一个 JS 函数通过 setTimeout 每隔几毫秒触发一次。由于 JS 速度较慢,并且无法保证一致的触发——尤其是在移动设备上——你会得到明显的抖动。 CSS3 过渡是在本机代码中实现的,几乎总是看起来很流畅。
  • 非常感谢!我会查找 CSS3 过渡!

标签: javascript jquery toggle


【解决方案1】:

这是一个 CSS3 动画示例,它将帮助您实现滑动菜单。我不确定你的菜单会如何表现,但我认为这会给你一个很好的起点。 https://jsfiddle.net/jtholla2/73a7czm9/1/

* {
  margin: 0;
  padding: 0;
  font-family: "Helvetica Neue", Helvetica, Sans-serif;
  word-spacing: -2px;
}
h1 {
  font-size: 40px;
  font-weight: bold;
  color: #191919;
  -webkit-font-smoothing: antialiased;
}
h2 {
  font-weight: normal;
  font-size: 20px;
  color: #888;
  padding: 5px 0;
}
.menu {
  background: #181818;
  color: #FFF;
  position: absolute;
  top: -250px;
  left: 0;
  width: 100%;
  height: 250px;
  padding: 20px;
  transition: 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
  overflow: hidden;
  box-sizing: border-box;
}
.menu h1 {
  color: #FFF;
}
#toggle {
  position: absolute;
  appearance: none;
  cursor: pointer;
  left: -100%;
  top: -100%;
}
#toggle + label {
  position: absolute;
  cursor: pointer;
  padding: 10px;
  background: #26ae90;
  width: 100px;
  border-radius: 3px;
  padding: 8px 10px;
  color: #FFF;
  line-height: 20px;
  font-size: 12px;
  text-align: center;
  -webkit-font-smoothing: antialiased;
  cursor: pointer;
  margin: 20px 50px;
  transition: all 500ms ease;
}
#toggle + label:after {
  content: "Open"
}
.container {
  transition: margin 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
  padding: 5em 3em;
}
#toggle:checked ~ .menu {
  top: 0;
}
#toggle:checked ~ .container {
  margin-top: 250px;
}
#toggle:checked + label {
  background: #dd6149;
}
#toggle:checked + label:after {
  content: "Close"
}
<input type="checkbox" name="toggle" id="toggle" />
<label for="toggle"></label>

<div class="container">
  <h1>CSS3 Slide Down Toggle Demo Menu</h1>
  <h2>Click the Open button to see the menu.</h2>
</div>

<div class="menu">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
    <li>Item Four</li>
  </ul>
</div>

【讨论】:

  • 如果我稍微修改一下这段代码,是否可以让菜单也从左侧或右侧滑入?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多