search
HomeWeb Front-endJS TutorialDetailed explanation of Bootstrap scroll monitoring (Scrollspy) plug-in_javascript skills

Scroll spy (Scrollspy) plug-in, that is, the automatic update navigation plug-in, will automatically update the corresponding navigation target according to the position of the scroll bar. Its basic implementation is to add an .active class to the navigation bar based on the position of the scroll bar as you scroll.

If you want to reference the functionality of this plugin separately, then you need to reference scrollspy.js. Alternatively, as mentioned in the Bootstrap plugin overview chapter, you can reference bootstrap.js or a minified version of bootstrap.min.js.

1. Usage
You can add scroll listening behavior to the top navigation:

1. Through the data attribute: add data-spy="scroll" to the element you want to monitor (usually body). Then add an attribute data-target with the ID or class of the parent element of the Bootstrap .nav component. For this to work, you must ensure that an element exists in the body of the page that matches the ID of the link you want to listen for.

<body data-spy="scroll" data-target=".navbar-example">
 ...
 <div class="navbar-example">
  <ul class="nav nav-tabs">
   ...
  </ul>
 </div>
 ...
</body>

2. Through JavaScript: You can call scroll monitoring through JavaScript, select the element to be monitored, and then call the .scrollspy() function:
$('body').scrollspy({ target: '.navbar-example' })
2. Scroll monitoring
The scroll listening plug-in is used to automatically update navigation items based on the position of the scroll bar and display navigation item highlights.

//基本实例
<nav id="nav" class="navbar navbar-default">
  <a href="#" class="navbar-brand">Web 开发</a>
  <ul class="nav navbar-nav">
    <li>
      <a href="#html5">HTML5</a>
    </li>
    <li>
      <a href="#bootstrap">Bootstrap</a>
    </li>
    <li class="dropdown">
      <a href="#" data-toggle="dropdown">JavaScript <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li>
          <a href="#jquery">jQuery</a>
        </li>
        <li>
          <a href="#yui">Yui</a>
        </li>
        <li>
          <a href="#extjs">Extjs</a>
        </li>
      </ul>
    </li>
  </ul>
</nav>

<div data-offset="0" data-target="#nav" data-spy="scroll" style="height: 200px; overflow: auto; position: relative;padding: 0 10px;">
  <h4 id="HTML">HTML5</h4>
  <p>
    标准通用标记语言下的一个应用 HTML 标准自 1999 年 12 月发布的 HTML4.01后,后继的 HTML5 和其它标准被束之高阁,为了推动 Web 标准化运动的发展,一些公司联合起来,成立了一个叫做 Web Hypertext Application Technology Working Group(Web 超文本应用技术工作组 -WHATWG) 的组织。WHATWG 致力于 Web 表单和应用程序,而 W3C(World Wide Web Consortium,万维网联盟) 专注于 XHTML2.0。在 2006 年,

    双方决定进行合作,来创建一个新版本的 HTML。
  </p>
  <h4 id="Bootstrap">Bootstrap</h4>
  <p>
    Bootstrap,来自 Twitter,是目前很受欢迎的前端框架。Bootstrap 是基于 HTML、 CSS、 JAVASCRIPT 的, 它简洁灵活, 使得 Web 开发更加快捷。 [1]它由 Twitter的设计师 Mark Otto 和 Jacob Thornton 合作开发,是一个 CSS/HTML 框架。Bootstrap提供了优雅的 HTML 和 CSS 规范,它即是由动态 CSS 语言 Less 写成。Bootstrap 一经推出后颇受欢迎,一直是 GitHub 上的热门开源项目,包括 NASA 的 MSNBC(微软全国广播公司)的 Breaking News 都使用了该项目。[2]国内一些移动开发者较为熟悉的框架,如 WeX5前端开源框架等,也是基于 Bootstrap 源码进行性能优化而来。[3]
  </p>
  <h4 id="jQuery">jQuery</h4>
  <p>
    JQuery 是继 prototype 之后又一个优秀的 Javascript 库。 它是轻量级的 js库 ,它兼容 CSS3,还兼容各种浏览器(IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+) ,jQuery2.0 及后续版本将不再支持 IE6/7/8 浏览器。jQuery 使用户能更方便地处理 HTML(标准通用标记语言下的一个应用) 、 events、 实现动画效果, 并且方便地为网站提供 AJAX交互。jQuery 还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。 jQuery 能够使用户的 html 页面保持代码和 html 内容分离, 也就是说, 不用再在 html 里面插入一堆 js 来调用命令了, 只需要定义 id 即可。
  </p>
  <h4 id="Yui">Yui</h4>
  <p>
    近几年随着 jQuery、Ext 以及 CSS3 的发展,以 Bootstrap 为代表的前端开发框架如雨后春笋般挤入视野, 可谓应接不暇。 不论是桌面浏览器端还是移动端都涌现出很多优秀的框架,极大丰富了开发素材,也方便了大家的开发。这些框架各有特点,本文对这些框架进行初步的介绍与比较, 希望能够为大家选择框架提供一点帮助, 也为后续详细研究这些框架的抛砖引玉。
  </p>
  <h4 id="Extjs">Extjs</h4>
  <p>
    ExtJS 可以用来开发 RIA 也即富客户端的 AJAX 应用,是一个用 javascript写的,主要用于创建前端用户界面,是一个与后台技术无关的前端 ajax 框架。因此,可以把 ExtJS 用在.Net、Java、Php 等各种开发语言开发的应用中。ExtJs 最开始基于 YUI 技术,由开发人员 JackSlocum 开发,通过参考 JavaSwing 等机制来组织可视化组件,无论从 UI 界面上 CSS 样式的应用,到数据解析上的异常处理,都可算是一款不可多得的JavaScript 客户端技术的精品。
  </p>
</div>

There are two important attributes here, as shown below:


PS: In a menu and a simple situation, scrolling monitoring highlighting can be stably implemented without data-target setting. But when there are multiple navigations, if you don't associate one of them, it will cause an error, so it is generally necessary to add it.

If you use JavaScript scripting, you can remove data-* and use script attributes to define: offset, spy and target. The specific method is as follows:

//使用脚本方式定义属性

$('#content').scrollspy({
  offset : 0,
  target : '#nav',
}); 

The scroll listener also has an event to switch to a new item.

//The event is bound to the navigation

$('#nav').on('activate.bs.scrollspy', function() {
alert('This event is triggered after the new entry is activated!');
});
The scroll listener also has a method that updates the container DOM.

//HTML part

<section class="sec">
  <h4 id="HTML-a-href-onclick-removeSec-this-删除此项-a">HTML5 <a href="#" onclick="removeSec(this)">删除此项</a></h4>
  <p>
    ...
  </p>
</section>

//When deleting content, refresh the DOM to avoid navigation monitoring misplacement

function removeSec(e) {
  $(e).parents('.sec').remove();
  $('#content').scrollspy('refresh');
}

Note: This method must use the data-* declaration.

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software