Home > Web Front-end > JS Tutorial > body text

Javascript implements ceiling effect (code example)

不言
Release: 2020-02-27 13:39:11
forward
3146 people have browsed it

What this article brings to you is Javascript to implement ceiling effects (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Javascript implements ceiling effect (code example)

Knowledge points

1. Combined use of scroll family and offset family

2. When the offsetTop of the nav is greater than the height of the screen scrolling, perform ceiling lifting

3. Add a fixed class. If the conditions are met, add a class name to the nav

Running effect

Javascript implements ceiling effect (code example)

When scrolling the page, ensure that the navigation bar is ceiling-mounted

Javascript implements ceiling effect (code example)

Code:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title></title>
 <style>
 *{margin: 0;padding: 0;list-style: none;border:none}
 img{vertical-align: top;width: 100%;}
 section{width: 70%;margin: 0 auto;}
 .nav{position: fixed;left: 0;top: 0;width: 100%}
 </style>
</head>
<body>
 <header id="head">
 <img src="images/top.png" alt="">
 </header>
 <nav id="nav">
 <img src="images/nav.png" alt="">
 </nav>
 <section>
 <img src="images/body01.png" alt="">
 <img src="images/body02.png" alt="">
 </section>
 <script src="../../MyTools/MyTools.js"></script>
 <script>
 window.addEventListener(&#39;load&#39;,function (ev) {
  // 1. 求出头部高度
  var navTopHeight = myTool.$(&#39;nav&#39;).offsetTop;
  // 2. 监听页面滚动
  window.addEventListener(&#39;scroll&#39;,function (ev1) {
  var scrollTopHeight = myTool.scroll().top;
  // 2.1 判断
  if(scrollTopHeight >= navTopHeight){
   myTool.addClassName(myTool.$(&#39;nav&#39;),&#39;nav&#39;)
  }else{
   myTool.removeClassName(myTool.$(&#39;nav&#39;),&#39;nav&#39;);
  }
  })
 })
 </script>
</body>
</html>
Copy after login

More cool javascript special effects codes, all in: js special effects collection

The above is the detailed content of Javascript implements ceiling effect (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!