如何在向下滚动时使元素消失并重新出现?

时间:2014-04-03 15:05:59

标签: javascript jquery html css

所以在我的网站上,我在顶部有一个固定的栏,横跨页面的长度,栏是一个h1。附有一个迷你导航,后面和主页按钮位于它下面,也是固定的。当您向下滚动时,迷你导航在阅读页面内容时会受到阻碍,因此我想在用户向下滚动时使导航消失,并且还可以通过将鼠标移到顶部/单击顶部来重新显示导航吧/在触摸屏上刷顶栏等等。

我该怎么做呢?

这是HTML:

<header class="mainHeader">
  <h1>Page Title</h1>
    <nav class="secondaryNav">
      <a href="home.htm"><img class="backButton" src="img/back2.png" alt="Back Button"></a>
      <a href="home.htm"><img class="homeButton" src="img/home.png" alt="Home Button"></a>
    </nav>
    <aside><p id="countdown"></p></aside>
</header>
<!-- end .mainHeader -->

CSS:

.mainHeader h1 {
    position: fixed;
    top: 0;
    width: 100%;
    background: #ea594e;
    box-shadow: 0 0 3px 3px #888888;
    font-family: verdana;
    font-variant: small-caps;
    color: white;
    border-bottom: 1px solid black;
    margin: 0;
    padding-bottom: 0.5%;
    text-align: center;
}

.mainHeader .secondaryNav {
    background: #ffcda4;
    box-shadow: 0 3px 3px 1px #888888;
    border: 1px solid;
   border-top: none;
    width: 400px;
    position: fixed;
    top: 49px;
    left: 50%;
    margin-left: -200px;
    border-radius: 0 0 50px 50px;
    padding-top: 5px;
}

栏是h1,迷你导航是secondaryNav

3 个答案:

答案 0 :(得分:0)

您可以使用scrollTop并检查用户向下滚动的内容,如

$(function() {
  $(document).on("mousewheel", function() {
    if($(document).scrollTop() > 100){
        $('.secondaryNav').show();
        $('.mainHeader h1').hide();
    } else {
        $('.secondaryNav').hide();
        $('.mainHeader h1').show();
    }; 
  });
});

这是工作Fiddle(稍微更改css以使其看起来更好,但重点是那里)

答案 1 :(得分:0)

这个简单的代码可能对你有帮助。的 JSFIDDLE

 //Keep track of last scroll
          var lastScroll = 0;
          $(window).scroll(function(event){
              //Sets the current scroll position
              var st = $(this).scrollTop();
              //Determines up-or-down scrolling
              if (st > lastScroll){
//secondaryNav disappears when scrolled down
                $(".secondaryNav").css("display","none");
              } 
              else {
//secondaryNav disappears when scrolled up
               $(".secondaryNav").css("display","block");
              }
              //Updates scroll position
              lastScroll = st;
          });

答案 2 :(得分:0)

这是在鼠标移动时显示和隐藏特定div的简单且通常有用的方法:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
</style>
</head>
<body>


<button onmousewheel="myFunction()">wheel mouse on me to hide and show div</button>

<div id="myDIV">
This is my DIV element.
</div>

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

<script>
function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

</body>
</html>