Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

  • Hi, I’m _Peach and today I’m going to talk about a common ‘top suction’ implementation for work

What is the top effect

Rolling to a certain height will stick to the top

  • Before rolling

  • After rolling

How to achieve the top suction effect

  1. throughwindow.addEventListener("scroll", this.initHeight);Event listener scroll
  2. Determine whether to add a class name based on its height
  3. Vue is used herev-bindSyntactic sugar: :class="{'is_fixed': isfixed}"
  4. Class names are controlled by variables
  5. Leave the page when passing through the vUE lifecycledestroyed()Scroll event after instance destruction

Code implementation

HTML structure

<div class="index">
    <div class="navHeader">
      <div class="container"><h1>I am a head</h1></div>
    </div>
    <div class="top" :class="{ is_Fixed: isFixed }">
      <div class="container"><h2>Top suction function realization</h2></div>
    </div>
    <div class="wrapper">
      <div class="container">
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
      </div>
    </div>
  </div>
Copy the code

Js implementation

export default {
  name: 'index'.data() {
    return {
      isFixed: false}},mounted() {
    window.addEventListener('scroll'.this.initHeight)
  },
  methods: {
    initHeight() {
      let scrollTop =document.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop // Get the page height
      this.isFixed = scrollTop > 80 ? true : false // Controls whether the class name is displayed}},destroyed() {
    window.removeEventListener('scroll'.this.initHeight) // Destroy clears scroll event}}Copy the code

CSS styles

<style lang="less">
*{
  padding: 0;
  margin: 0;
}
.home {
  height: 500px;
  .navHeader {
    height: 80px;
    padding-top: 10px;
    text-align: center;
    color: # 0009.background: #ccc;
  }
  .top {
    height: 60px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    line-height: 60px;
    color: #fff;
    background: #f60;
    &.is_Fixed {
      position: fixed;
      top: 0;
      width: 100%; }}p {
    height: 150px;
    margin: 10px 0; }}.container {
  width: 1226px;
  margin-left: auto;
  margin-right: auto;
}
</style>

Copy the code

conclusion

That’s all for today’s sharing. Let’s work hard