【问题标题】:navigation hide menu with jQuery使用 jQuery 的导航隐藏菜单
【发布时间】:2019-10-12 05:37:43
【问题描述】:

我用 jquery 构建了一个导航菜单,当我点击菜单图标时它会打开,但是当我再次点击菜单图标时它不会关闭

这是html代码:

<aside class="aside_menu">
        <span class="arrow"></span>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
</aside>

这是jquery代码:

$(document).ready(function () {
$(".aside_menu .arrow").click(function () {
    var aside_menu = $(this).parent();
    if (aside_menu.offset().right === 0)
        aside_menu.animate({right: "-200px"})
    else
        aside_menu.animate({right: "0px"})
})

})

菜单隐藏在页面右侧,只显示菜单图标

对不起,语言不好

【问题讨论】:

    标签: javascript jquery html css menu


    【解决方案1】:

    .offset() 返回一个包含属性topleft 的对象,因此您的代码将永远无法工作,因为aside_menu.offset().right 始终未定义。见http://api.jquery.com/offset/

    您必须使用aside_menu.offset().left,然后根据您的页面布局在if 条件中找到合适的值。

    【讨论】:

    • 有修复的替换代码吗?我的页面是 rtl,我需要在页面的右侧
    • 我不确定是否有解决此问题的简单方法,但您可以尝试使用$(document).width() 进行一些数学运算以获取和设置导航的位置。
    【解决方案2】:

    在最大阻力线之后的简单的事情,而不是jQuery,这种简单的事情最好用JS。此外,JS 中的动画很笨拙,尤其是在性能较弱的电脑和智能手机上,这会破坏用户体验。使用简单的 JS 和 CSS 更容易做到这一点。可能我的代码对你没有帮助,但我希望能引导你走上正确的道路。 附言。尽量不要在classes和attributes和id中使用:“_”(下划线),因为它是在SEO方面,它是在膝盖上的一个镜头,更好的选择是:“-”(破折号)。

    var menu = document.querySelector("#menu");
    var button = document.querySelector("#button");
    
    function toggleMenu(){
    	if(!menu.classList.contains("fade")){
      	menu.classList.add("fade");
      }else{
      	menu.classList.remove("fade");
      }
    }
    
    button.addEventListener("click", toggleMenu);
    body{
      margin: 0;
      display: flex;
      }
    #menu{
      background: pink;
      width: 70px;
      height: 100%;
      text-align: center;
      transition: 0.34s;
      }
    #button{
      height: 30px;
      transition: 0.34s;
      }
    .fade{
      width: 0 !important;
      }
    .fade *{
      display: none;
    }
    <aside id="menu" class="fade">
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
            <div><a href="#">test</a></div>
    </aside>
    <button id="button">
    Button
    </button>

    【讨论】:

      猜你喜欢
      • 2017-07-24
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2015-11-04
      • 2021-10-20
      • 1970-01-01
      相关资源
      最近更新 更多