html 如何让我的Div Box顺利滑入和滑出Body?

s4n0splo  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(104)

我试图让一个div框在我点击一个按钮时移入移出body元素。到目前为止,我的代码只能使div框平滑地滑入,但当滑出时,它会立即消失。
我把代码放在JSFiddle里了。

<!DOCTYPE html>
<html>

  <head>
    <title>test</title>
    <link rel="stylesheet" href="src/css/style.css">
  </head>

  <body>
    <button class="nav-button" type="button" onclick="showNav(this)">=</button>
    <span class="header">
      <h1 class="title">Title here</h1>
    </span>
    <div id="list-of-nav">
      <p>Navigation</p>
    </div>
    <script src="src/js/index.js"></script>
  </body>

</html>
var navShowCount = 0;
var speed = 10;

function showNav() {
  var nav = document.getElementById("list-of-nav");
  if (navShowCount % 2 == 0) {
    nav.style.left = "-300px";
    nav.style.display = "inline";
    let navLeftPos = nav.offsetLeft;
    nav.style.left = (navLeftPos + 300) + 'px';
  } else {
    nav.style.left = "0px"; //problem around here?
    let navLeftPos = nav.offsetLeft;
    nav.style.left = (navLeftPos - 150) + 'px';
    nav.style.display = "none";
  }
  navShowCount++;
}

期望我的div框能顺利地滑进滑出,但它只适用于滑进,而不是滑出。
我试过修改JavaScript代码,但仍然无法使其顺利滑出,请帮助

ajsxfq5m

ajsxfq5m1#

试试这个

var navShowCount = 0;
var speed = 10;

function showNav() {
  var nav = document.getElementById("list-of-nav");
  if (navShowCount % 2 == 0) {
    nav.style.left = "-300px";
    nav.style.display = "inline";
    let navLeftPos = nav.offsetLeft;
    nav.style.left = (navLeftPos + 300) + 'px';
  } else {
    nav.style.left = "-300px";
    let navLeftPos = nav.offsetLeft;
  }
  navShowCount++;
}
* {
  color: whitesmoke;
}

body {
  background-color: rgb(44, 44, 44);
  margin: 12px;
}

.header {
  display: flex;
  justify-content: center;
}

.nav-button {
  border: none;
  background-color: rgb(44, 44, 44);
  padding: 20px 20px;
  float: left;
  transition-duration: 0.4s;
}

.nav-button:hover {
  background-color: purple;
  border: 2px solid whitesmoke;
}

#list-of-nav {
  display: block;
  position: absolute;
  left: -300px;
  z-index: 1000;
  background-color: whitesmoke;
  width: 300px;
  transition: left 0.3s 0.1s ease-out;
}

#list-of-nav * {
  color: rgb(44, 44, 44);
  text-align: center;
}
<!DOCTYPE html>
<html>

  <head>
    <title>test</title>
    <link rel="stylesheet" href="src/css/style.css">
  </head>

  <body>
    <button class="nav-button" type="button" onclick="showNav(this)">=</button>
    <span class="header">
      <h1 class="title">Title here</h1>
    </span>
    <div id="list-of-nav">
      <p>Navigation</p>
    </div>
    <script src="src/js/index.js"></script>
  </body>

</html>

相关问题