首页 > 解决方案 > 如何在我的侧面导航中使用 CSS 和 Javascript 添加从左到右的平滑滑动效果?

问题描述

我正在尝试制作 CSS 和 JavaScript 侧导航。这是我到目前为止的代码:

var nav = document.getElementById('nav');
function show(){
nav.style.display = "block";
}
.side-nav{
background-color:black;
height:100%;
width:250px;
position: absolute;
display:none;
}
#myLink{

color:gray;
text-decoration: none;
display:block;
margin-left:15px;
margin-bottom:10px;
font-size:25px;
transition: .5s;
font-family: 'Marck Script', cursive;
margin-top:10px;

}
#myLink:hover{
  color:white;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css2?family=Marck+Script&display=swap" rel="stylesheet">
  </head>
  <body>
    <div class = "side-nav" id = "nav">
<div id = "myLinks">

<a href = "#" id = "myLink">Home</a>
<a href = "#" id = "myLink">Contact</a>
<a href = "#" id = "myLink">Blog</a>
<a href = "#" id = "myLink">Products</a>

</div>



    </div>
    <a href = "#" onclick = "show();">Show nav</a>
    <script src="script.js"></script>
    
  </body>
</html>

如何使用侧导航实现从左到右的平滑滑动?我还需要使用 JavaScript 吗?或者有什么方法可以只用 CSS 来做到这一点?提前致谢!!!

标签: javascripthtmlcss

解决方案


你想要这样吗?

var nav = document.getElementById('nav');
function show(){
nav.classList.toggle("active");
}
.side-nav{
background-color:black;
height:100%;
width:250px;
position: absolute;
display:none;
}
#myLink{

color:gray;
text-decoration: none;
display:block;
margin-left:15px;
margin-bottom:10px;
font-size:25px;
transition: .5s;
font-family: 'Marck Script', cursive;
margin-top:10px;

}
#myLink:hover{
  color:white;
}

.side-nav.active{
   display:block;
   animation:animate 1s linear forwards;
}

@keyframes animate{
   from{
      opacity:0;
       width:0;
   }
   to{
   width:250px;
   opacity:1;
   }
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css2?family=Marck+Script&display=swap" rel="stylesheet">
  </head>
  <body>
    <div class = "side-nav" id = "nav">
      <div id = "myLinks">
        <a href = "#" id = "myLink">Home</a>
        <a href = "#" id = "myLink">Contact</a>
        <a href = "#" id = "myLink">Blog</a>
        <a href = "#" id = "myLink">Products</a>
      </div>
    </div>
    <a href = "#" onclick = "show();">Show nav</a>
    <script src="script.js"></script>
  </body>
</html>


推荐阅读