2 回答
TA贡献1850条经验 获得超11个赞
您的代码确实有效,但您需要使代码可见,以便您可以单击它。不漂亮,但显示了它是如何工作的:.toggle
$(function() {
$('.toggle').on('click', function() {
$('.wrapper').toggleClass('open');
});
});
.wrapper {
transform: translateX(0px);
transition: transform .4s ease;
}
.wrapper.open {
transform: translateX(280px);
}
#main-nav {
transform: translateX(-280px);
}
.toggle {
background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<nav id="main-nav">
<div class="menu-btn toggle">|Menu|</div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</nav>
</div>
TA贡献1868条经验 获得超4个赞
你的代码似乎几乎可以工作,因为JQuery丢失了,在这种情况下,我稍微重写了一下。还需要为菜单和按钮添加一些内容以使其可见。您显示的代码不足以重现问题。;)
出于可访问性原因(对键盘交互的本机支持),我还建议对此类交互使用实际的按钮标记。
如果您有兴趣:https://developer.mozilla.org/en-US/docs/Learn/Accessibility/HTML
const body = document.body; // Get the document body
// Get your menu with a special JS class, prevents accidents when other
// developers will use your code later on (seperate JS functions from styling classes).
const menuToggle = document.querySelector('.js-site-menu');
// Set a classname to use lateron (DRY).
const menuToggleClass = "is-open";
// Add event to listen to.
menuToggle.addEventListener("click", (event) => {
// Get current clicked object/target.
let currentTarget = event.currentTarget;
// Check if opened class is present on body
let menuOpened = body.classList.contains(`${menuToggleClass}`);
// Check if menu is already open.
if (!menuOpened) {
// Adds class to body when not opened
body.classList.add(`${menuToggleClass}`);
} else {
// Removes class from body when menu is already opened
body.classList.remove(`${menuToggleClass}`);
}
});
`/* Used percentages(%) instead of a fixed px size for easier responsive behaviour later on the road. */`
.main-nav {
transform: translateX(-101%);
transition: transform .4s ease;
}
.is-open .main-nav {
transform: translateX(0%);
}
.main-nav_button {
position: absolute;
top: 0;
right: 0;
}
<div class="wrapper">
<button type="button" class="main-nav_button js-site-menu">Menu</button>
<nav class="main-nav">
<ul>
<li>Menu item 1</li>
<li>Menu item 2</li>
<li>Menu item 3</li>
<li>Menu item 4</li>
</ul>
</nav>
</div>
添加回答
举报