我无法使侧边栏按钮在 HTML、CSS 中沿着侧边栏移动

您好,我正在尝试为我的网站创建一个侧边栏,该侧边栏具有随其移动的打开/关闭按钮。

我的代码基于w3school的示例,该示例中有两个单独的按钮用于打开和关闭。我不喜欢有两个单独的按钮来完成任务,并且想将它们组合起来。所以我将示例修改为:

如果您尝试运行代码,那么当您第一次单击该按钮时,侧边栏将打开并且按钮也会随之打开。这很棒,也是我想要的,问题是关闭侧边栏时按钮不会返回到其原始位置。侧边栏打开和关闭没有问题,但似乎这行代码不起作用

document.getElementById("sidebarButton").style.Left = "0px";

知道如何修复它吗?


蓝山帝景
浏览 105回答 2
2回答

胡说叔叔

尽管样式属性在样式表内部不区分大小写,但样式的 JavaScript API 区分大小写。因此,设置style.Left将不起作用,因为正确的属性名称是left。document.getElementById("sidebarButton").style.left = '0';

暮色呼如

你有一个拼写错误document.getElementById("sidebarButton").style.Left应该是document.getElementById("sidebarButton").style.leftvar lastState = false;function sideButtonClicked() {&nbsp; if (!lastState) {&nbsp; &nbsp; //open&nbsp; &nbsp; lastState = true&nbsp; &nbsp; document.getElementById("mySidebar").style.width = "250px";&nbsp; &nbsp; document.getElementById("main").style.marginLeft = "250px";&nbsp; &nbsp; document.getElementById("sidebarButton").style.left = "250px";&nbsp; } else {&nbsp; &nbsp; //close&nbsp; &nbsp; lastState = false&nbsp; &nbsp; document.getElementById("mySidebar").style.width = "0px";&nbsp; &nbsp; document.getElementById("main").style.marginLeft = "0px";&nbsp; &nbsp; document.getElementById("sidebarButton").style.left = "0px";&nbsp; }}body {&nbsp; font-family: "Lato", sans-serif;}.sidebar {&nbsp; height: 100%;&nbsp; width: 0;&nbsp; position: fixed;&nbsp; z-index: 1;&nbsp; top: 0;&nbsp; left: 0;&nbsp; background-color: #111;&nbsp; overflow-x: hidden;&nbsp; transition: 0.5s;&nbsp; padding-top: 60px;}.sidebar a {&nbsp; padding: 8px 8px 8px 32px;&nbsp; text-decoration: none;&nbsp; font-size: 25px;&nbsp; color: #818181;&nbsp; display: block;&nbsp; transition: 0.3s;}.sidebar a:hover {&nbsp; color: #f1f1f1;}.openbtn {&nbsp; font-size: 20px;&nbsp; cursor: pointer;&nbsp; position: fixed;&nbsp; bottom: 50%;&nbsp; left: 0;&nbsp; background-color: #111;&nbsp; color: white;&nbsp; padding: 10px 15px;&nbsp; border: none;&nbsp; z-index: 1;&nbsp; transition: 0.5s;}.openbtn:hover {&nbsp; background-color: #444;}#main {&nbsp; transition: margin-left .5s;&nbsp; padding: 16px;}/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */@media screen and (max-height: 450px) {&nbsp; .sidebar {&nbsp; &nbsp; padding-top: 15px;&nbsp; }&nbsp; .sidebar a {&nbsp; &nbsp; font-size: 18px;&nbsp; }}<div id="mySidebar" class="sidebar">&nbsp; <a href="#">About</a>&nbsp; <a href="#">Services</a>&nbsp; <a href="#">Clients</a>&nbsp; <a href="#">Contact</a></div><div id="main">&nbsp; <button id="sidebarButton" class="openbtn" onclick="sideButtonClicked()">☰</button>&nbsp; <h2>Collapsed Sidebar</h2>&nbsp; <p>Click on the hamburger menu/bar icon to open the sidebar, and push this content to the right.</p></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5