Table of Contents
html structure
Home Web Front-end JS Tutorial vue uses native js to implement scrolling page tracking and navigation highlighting

vue uses native js to implement scrolling page tracking and navigation highlighting

Oct 25, 2018 pm 03:17 PM
css html5 javascript vue.js

The content of this article is about Vue using native js to implement scrolling page tracking and navigation highlighting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

You need to use vue to make a special page.

Scroll the page and highlight the navigation in the specified area.

Listen to scrolling page events, compare the position of the current page with the position of the element, if the current scrolling area position is greater than the position of the element, add a class to the navigation, otherwise remove the class for style switching.

The method I use is to add the id to the positioning element, add the data-id attribute to the navigation, listen for the scroll event, and if the current scroll area is larger than the positioning element area, assign the element's id to the variable, and then combine it with the navigation's data- Match the id and switch the class.

html structure

main.vue

<template>
  <div class="qz-home">
    <div class="quiz-container">
      <div class="quiz-ad-pic" id="pagetop"></div>
      <div class="quiz-main">
        <div class="quiz-main-inside" id="js-content">
          <quiz-sessions class="item" id="quizhall"></quiz-sessions>
          <quizRecords class="item" id="quizrecord"></quizRecords>
          <quiz-history class="item" id="quizHistory"></quiz-history>
          <quiz-mine class="item" id="quizMine"></quiz-mine>
          <quiz-rank class="item" id="quizRank"></quiz-rank>
          <quiz-rule class="item" id="quizRule"></quiz-rule>
        </div>
      </div>
      <navigation id="js-nav"></navigation>
    </div>
  </div>
</template>
Copy after login

navigation.vue

<template>
  <nav class="nav-container">
    <div class="nav-mark"></div>
    <div class="nav-main">
      <ul class="nav-list">
        <li :class="{&#39;cur&#39;: curindex === index}" v-for="(item, index) in navList" :key="index" :data-id="item.id"><a @click="linkTo(item.id, index)">{{item.name}}</a></li>
      </ul>
      <div class="backtop" @click="backTop()">
        <a></a>
      </div>
    </div>
  </nav>
</template>
Copy after login

javascript

export default {
  name: "Navigation",
  data() {
    return {
      navList: [
        { name: "竞猜大厅", id: "quizhall" },
        { name: "竞猜记录", id: "quizrecord" },
        { name: "历史赛事", id: "quizHistory" },
        { name: "我的竞猜", id: "quizMine" },
        { name: "排行榜", id: "quizRank" },
        { name: "玩法", id: "quizRule" }
      ],
      curindex: 0
    };
  },
  mounted() {
    this.initScroll();
  },
  methods: {
    initScroll() {
      let _this = this;
      // 监听页面滚动事件
      window.addEventListener('scroll', function() {
        var removeClass = function(obj, cls) {
          if (obj.className == cls) {
            obj.className = "";
          }
        }
        var addClass = function(obj, cls) {
          if (obj.className != cls) {
            obj.className = cls;
          }
        }

        let pos = document.documentElement.scrollTop;
        if (pos > 300) {
          _this.isVisibleNav = true;
        } else {
          _this.isVisibleNav = false;
        }
        // 获取全部导航dom与元素dom
        var navList = document.querySelector("#js-nav").querySelectorAll("li");
        var items = document.querySelector("#js-content").querySelectorAll(".item");
        // 滚动后遍历元素,如果页面滚动位置大于元素的位置,赋值给变量
        var currentId = "";
        for (var i = 0; i < items.length; i++) {
          var _item = items[i];
          var _itemTop = _item.offsetTop;
          if (pos > _itemTop - 200) {
            currentId = _item.id;
          } else {
            break;
          }
        }
        // 如果已赋值了变量,进行匹配,如果匹配则添加class其他删除
        if (currentId) {
          for (var j = 0; j < navList.length; j++) {
            var _navItem = navList[j];
            var _navId = _navItem.getAttribute('data-id');
            if (_navId != currentId) {
              removeClass(_navItem, "cur");
            } else {
              addClass(_navItem, "cur");
            }
          }
        }
      })
    }
  }
};
Copy after login

The above is the detailed content of vue uses native js to implement scrolling page tracking and navigation highlighting. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

See all articles