平滑切换 Javascript 功能
好吧,我想做的是点击时切换菜单,但它不平滑,感觉很难,我是 JS 新手,但我对 CSS 和 HTML 足够了解,所以有没有办法平滑这个切换功能?
未单击的菜单:
单击的菜单:
const toggleButton = document.getElementsByClassName("nav__toggle-button")[0];
const navbarLinks = document.getElementsByClassName("nav__links")[0];
toggleButton.addEventListener("click", () => {
console.log("clicked");
navbarLinks.classList.toggle("active");
toggleButton.classList.toggle("open");
});
Well what I want to do is to toggle a menu when is clicked but it's not smooth and it feels tough, I'm a newbie in JS but I do know CSS and HTML well enough, so is there a way to smooth this toggle function?
menu unclicked:
menu clicked:
const toggleButton = document.getElementsByClassName("nav__toggle-button")[0];
const navbarLinks = document.getElementsByClassName("nav__links")[0];
toggleButton.addEventListener("click", () => {
console.log("clicked");
navbarLinks.classList.toggle("active");
toggleButton.classList.toggle("open");
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你想用CSS解决这个问题,你可以使用transitions属性对两个div进行“动画”处理: https ://www.w3schools.com/css/css3_transitions.asp
关闭状态:
打开状态:
两个未成年人:
不要使用 BEM 类来触发事件侦听器,而是使用适当的类(js-click 或其他东西..)
前两行的小重构:
If you want to solve this with CSS you can 'animate' the two divs with the transitions property: https://www.w3schools.com/css/css3_transitions.asp
close state:
open state:
Two minors:
don't use BEM classes to trigger an event listener, use instead a proper class (js-click or something..)
a small refactor for your first two lines:
您可以通过 CSS 将过渡和变换属性应用于元素。
例如,如果您使用下拉菜单并控制幻灯片和不透明度:
您可以查看:
https://developer.mozilla.org/en-US/docs/网页/CSS/过渡
You can apply transition and transform properties to the element through CSS.
For example, if you are using a drop down menu and controlling the slide and the opacity:
You could check out:
https://developer.mozilla.org/en-US/docs/Web/CSS/transition
您所需要的只是一个可以切换的过渡和变换属性。 Transform CSS 属性用于处理 DOM 元素的尺寸、方向等。添加过渡会增加变换属性如果更改则逐渐变化的效果。
All you need is a transition and transform property that you can toggle. Transform CSS property is used for handling dimensions, orientation etc of a DOM element. Adding transition adds an effect where the transform properties if changed, change gradually.