如何使用jquery和CSS隐藏和显示侧边栏?

时间:2019-01-13 22:23:12

标签: javascript jquery css html5

我希望能够在按下按钮时显示侧边栏,但似乎不起作用。

我有一个jQuery代码,可以在按下按钮和css内部时在类之间进行切换,它应该隐藏/显示侧边栏

html:

<div id="sidebar">
    <img src="img/MyPicture.png" alt="MyPicture" class="headshot"/>
    <span style="font-weight:bold">MyName</span>
    <ul class="menu">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</div>
<div id="wrapper">
    <div id="main">
        <div>
            <button id="sidebarToggle">Toggle Menu</button>
        </div>
        <h1>My Page</h1>
    </div>
    <div id="footer">
        <p>This is the footer</p>
        &copy; 2019 My Profile
    </div>
</div>

site.js:

var $sidebarAndWrapper = $("#sidebar,#wrapper");

$("#sidebarToggle").click(function () {
    $sidebarAndWrapper.toggleClass("hide-sidebar");
});

site.css:

#sidebar {
background:#17153e;
color:#c8c5d3;
position:fixed;
height:100%;
width:250px;
overflow:hidden;
left:0;
margin:0;
}

#sidebar.hide-sidebar {
    left: -250px;
}

#wrapper {
margin:0 0 0 250px;
}
    #wrapper.hide-sidebar {
    margin-left: 0;
}

1 个答案:

答案 0 :(得分:0)

您的工作对我来说很好,请检查您的Jquery链接。似乎未正确加载。我用了一个CDN下来,只是检查一下就可以了。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

  <style>

#sidebar {
background:#17153e;
color:#c8c5d3;
position:fixed;
height:100%;
width:250px;
overflow:hidden;
left:0;
margin:0;
}

#sidebar.hide-sidebar {
    left: -250px;
}

#wrapper {
margin:0 0 0 250px;
}
    #wrapper.hide-sidebar {
    margin-left: 0;
}
  </style>
</head>

<body>
    <div id="sidebar">
        <img src="img/MyPicture.png" alt="MyPicture" class="headshot"/>
        <span style="font-weight:bold">MyName</span>
        <ul class="menu">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </div>
    <div id="wrapper">
        <div id="main">
            <div>
                <button id="sidebarToggle">Toggle Menu</button>
            </div>
            <h1>My Page</h1>
        </div>
        <div id="footer">
            <p>This is the footer</p>
            &copy; 2019 My Profile
        </div>
    </div>
    <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
  <script>
 var $sidebarAndWrapper = $("#sidebar,#wrapper");

$("#sidebarToggle").click(function () {
    $sidebarAndWrapper.toggleClass("hide-sidebar");
});
  </script>


</body>

</html>