Skip to content
Advertisement

I want to make a message window in HTML but the javascript not work

I made a message window that will show a message when the user slide down the website and hide the message when the user slides up. I referenced this tutorial but it did not work as intended.

  • This is my code:
<html>
  <body onscroll="scroll()">
    <div
      id="message"
      style="position:fixed;left:0%;top:30%;height:20%,width:5%;border-radius:10px;background-image:linear-gradient(90deg,rgba(100,255,200,0.5),rgba(100,255,255,0.5),rgba(100,255,200,0.5));box-shadow: 10px 10px 10px 5px rgba(100,100,100,50);"
    >
      <p>
        testmessage:
      </p>
    </div>

    <script language="javascript">
      function scroll() {
        //console.log("打印log日志");实时看下效果
        //console.log("开始滚动!");
      }

      var scrollFunc = function (e) {
        e = e || window.event;
        if (e.wheelDelta) {
          //第一步:先判断浏览器IE,谷歌滑轮事件
          if (e.wheelDelta > 0) {
            //当滑轮向上滚动时
            //console.log("滑轮向上滚动");
            document.getElementById("message").width = 0;
            document.getElementById("message").height = 0;
          }

          if (e.wheelDelta < 0) {
            //当滑轮向下滚动时
            //console.log("滑轮向下滚动");
            document.getElementById("message").width = 20%;
            document.getElementById("message").height = 5%;
          }
        } else if (e.detail) {
          //Firefox滑轮事件
          if (e.detail > 0) {
            //当滑轮向上滚动时
            //console.log("滑轮向上滚动");
            document.getElementById("message").width = 0;
            document.getElementById("message").height = 0;
          }
          if (e.detail < 0) {
            //当滑轮向下滚动时
            //console.log("滑轮向下滚动");
            document.getElementById("message").width = 20%;
            document.getElementById("message").height = 5%;
          }
        }
      };
      //给页面绑定滑轮滚动事件
      if (document.addEventListener) {
        //firefox
        document.addEventListener("DOMMouseScroll", scrollFunc, false);
      }
      //滚动滑轮触发scrollFunc方法 //ie 谷歌
      window.onmousewheel = document.onmousewheel = scrollFunc;
    </script>
  </body>
</html>

I wonder what’s wrong with my code and how could I fix it.
Thank you.

Advertisement

Answer

You need to invoke your scrollFunc()

Add some height, so that it is scrollable.

    <body onscroll="scrollFunc()" style="height: 5000px;">
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement