search
HomeWeb Front-endJS TutorialImplementation of scroll monitor function in Bootstrap

Previous words

The scroll listening plug-in is used to automatically update navigation items based on the position of the scroll bar. Scroll the area below the navigation bar and pay attention to the changes in the navigation items. The items in the drop-down menu will also be automatically highlighted. This article will introduce in detail the Bootstrap scroll monitor

Basic usage

The scroll monitoring plug-in automatically updates the corresponding navigation items in the navigation bar based on the scrolling position. The plug-in can Automatically detect which position has been reached, and then add an active style

to the parent menu element that needs to be highlighted. If there is a drop-down menu in the navigation, and the content of the scroll area reaches the area corresponding to the sub-item of the drop-down menu, In addition to the submenu being highlighted, the parent element of the submenu (dropdown button) will also be highlighted

In daily use, scroll monitoring is generally used in two ways. One is to fix the height of an element. , scroll, and then highlight the corresponding menu; the other is to monitor the scrolling of the entire page (body). The usage of both methods is the same, and both require the following three steps:

1. Set the scroll container, that is, set data-target="#selector" data-spy="scroll" on the element you want to monitor. Attribute

 2. Set the menu link container. The id (or style) of the container must be consistent with the selector corresponding to the data-target attribute

 3. Within the menu container, there must be. A nav style element, and there is a li element in its content. The a element contained in li can also detect highlighted menu links, which meets the conditions of the .nav li > a selector

 4 . Regardless of the implementation method, the component that needs to be monitored for scroll monitoring is position: relative; That is, the relative positioning method

[Fixed element height]

<div> <ul>
<li><a>HTML</a></li>
<li><a>CSS</a></li>
<li><a>javascript</a></li> </ul>
</div><div>
<h4 id="Html">Html</h4>
<p>Html内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<h4 id="CSS">CSS</h4>
<p>CSS内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<h4 id="javascript">javascript</h4>
<p>javascript内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
</div>


[body element]

<div> <ul>
<li><a>HTML</a></li>
<li><a>CSS</a></li>
<li><a>javascript</a></li> </ul>
</div><h4 id="Html">Html</h4><p>Html内容</p><br><p>...</p><br><p>...</p><br><p>...</p><h4 id="CSS">CSS</h4><p>CSS内容</p><br><p>...</p><br><p>...</p><br><p>...</p><h4 id="javascript">javascript</h4><p>javascript内容</p><br><p>...</p><br><p>...</p><br><p>...</p><br><p>...</p><br><p>...</p><br><p>...</p>


##JS call

In the Bootstrap framework, it is relatively simple to use JavaScript methods to trigger the scroll monitor. You only need to specify the names of two containers.

<div> <ul>
<li><a>HTML</a></li>
<li><a>CSS</a></li>
<li><a>javascript</a></li> </ul>
</div><div>
<h4 id="Html">Html</h4>
<p>Html内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<h4 id="CSS">CSS</h4>
<p>CSS内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<h4 id="javascript">javascript</h4>
<p>javascript内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
</div><script>$(&#39;#scrollspy&#39;).scrollspy({ target: &#39;#myNavbar&#39; })    
</script>


Method

After adding or removing elements in the DOM while using the scroll listening plug-in, you need to call this refresh (refresh) method as follows

$('[data-spy="scroll"]').each(function () {  var $spy = $(this).scrollspy('refresh')
})
It should be noted that this refresh method is only valid for declarative usage. If you are using JS trigger and need to refresh the DOM, you need to re-apply the plug-in; or get the instance from the data-scrollspy attribute and then call the refresh method

[Parameter]

Parameters can be passed via data attributes or JavaScript. For the data attribute, its name is formed by appending the parameter name to

data-, for example data-offset=""

. Rolling monitoring provides an offset parameter, The default value of this parameter is 10. By default, if the scrolling content is within 10px of the scrolling container, the corresponding menu item will be highlighted

[Event]

Scroll monitoring also supports event subscription and triggering functions. Currently, only Support an activate event

activate.bs.scrollspy    每当一个新条目被激活后都将由滚动监听插件触发此事件。
<div> <ul>
<li><a>HTML</a></li>
<li><a>CSS</a></li>
<li><a>javascript</a></li> </ul>
</div><div>
<h4 id="Html">Html</h4>
<p>Html内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<h4 id="CSS">CSS</h4>
<p>CSS内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<h4 id="javascript">javascript</h4>
<p>javascript内容</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
<br><p>...</p>
</div><script>$(function(){
    $("#myNavbar").on(&#39;activate.bs.scrollspy&#39;,function(e){
        $(e.target).siblings().css(&#39;outline&#39;,&#39;none&#39;)
            .end().css(&#39;outline&#39;,&#39;1px solid black&#39;);    
    })
})    
</script>


##JS source code

【1】 IIFE

Use the immediate call function to prevent the code in the plug-in from leaking, thus forming a closed loop, and it can only be expanded from jQuery’s fn

+function ($) {//使用es5严格模式'use strict';//}(window.jQuery);
[2] Initial settings

  function ScrollSpy(element, options) {this.$body          = $(document.body)//判断滚动容器是否是body,如果是则使用window,如果不是则使用该元素本身this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)//将默认值和传进来的options参数合并,后者优先级高this.options        = $.extend({}, ScrollSpy.DEFAULTS, options)//如果option里设置了target,即data-target有值,则优先使用//如果没有,则查找通过.nav样式的子元素,即.nav样式内的li子元素内的a链接,作为菜单容器this.selector       = (this.options.target || '') + ' .nav li > a'this.offsets        = []this.targets        = []//高亮显示的菜单this.activeTarget   = nullthis.scrollHeight   = 0//给滚动容器绑定滚动事件this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))//计算当前页面内所有滚动容器内的id集合和每个id元素距离浏览器顶部的像素距离this.refresh()//开始正式处理this.process()
  }  //版本是3.3.7
  ScrollSpy.VERSION  = '3.3.7'  //默认值为offset:10
  ScrollSpy.DEFAULTS = {
    offset: 10
  }
【3】Plugin core code

  //获取滚动容器的滚动高度
  ScrollSpy.prototype.getScrollHeight = function () {//获取特定滚动容器的滚动高度,如果没有则获取body元素的滚动高度return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
  }

  ScrollSpy.prototype.refresh = function () {var that          = thisvar offsetMethod  = 'offset'var offsetBase    = 0this.offsets      = []this.targets      = []this.scrollHeight = this.getScrollHeight()if (!$.isWindow(this.$scrollElement[0])) {
      offsetMethod = 'position'  offsetBase   = this.$scrollElement.scrollTop()
    }this.$body
      .find(this.selector)
      .map(function () {var $el   = $(this)var href  = $el.data('target') || $el.attr('href')var $href = /^#./.test(href) && $(href)//返回一个二维数组,每个滚动容器内的id对象到页面顶部的距离以及高亮菜单容器里所对应的href值return ($href          && $href.length          && $href.is(':visible')          && [[$href[offsetMethod]().top + offsetBase, href]]) || null  })
      .sort(function (a, b) { return a[0] - b[0] })
      .each(function () {//收集所有的偏移值,也就是距离top的距离that.offsets.push(this[0])//收集菜单容器里的所有href值,也就是滚动容器里的id值that.targets.push(this[1])
      })
  }

  ScrollSpy.prototype.process = function () {//获取滚动容器的scrollTop,再加上设置的offset值var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset//获取滚动高度var scrollHeight = this.getScrollHeight()//最大滚动=总scrollheight + 设置的offset值 - 设置高度heightvar maxScroll    = this.options.offset + scrollHeight - this.$scrollElement.height()var offsets      = this.offsetsvar targets      = this.targetsvar activeTarget = this.activeTargetvar iif (this.scrollHeight != scrollHeight) {      this.refresh()
    }//如果超过了最大滚动,说明已经滚动到底了if (scrollTop >= maxScroll) {      //如果最后一个元素还没有高亮,则设置最后一个元素高亮  return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
    }if (activeTarget && scrollTop = offsets[i]//i+1元素不存在,或者i+1元素大于滚动高度&& (offsets[i + 1] === undefined || scrollTop <div class="cnblogs_code">【4】jQuery plug-in definition</div><p></p><pre class="brush:php;toolbar:false">  function Plugin(option) {//根据选择器,遍历所有符合规则的元素return this.each(function () {      var $this   = $(this)      //获取自定义属性bs.scrollspy的值  var data    = $this.data('bs.scrollspy')      //如果option参数是对象,则作为ScrollSpy的参数传入  var options = typeof option == 'object' && option      //如果值不存在,则将ScrollSpy实例设置为bs.scrollSpy值  if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))      //如果option传递了string,则表示要执行某个方法  if (typeof option == 'string') data[option]()
    })
  }  var old = $.fn.scrollspy  //保留其他库的$.fn.scrollspy代码(如果定义的话),以便在noConflict之后可以继续使用该老代码
  $.fn.scrollspy             = Plugin  //重设插件构造器,可以通过该属性获取插件的真实类函数
  $.fn.scrollspy.Constructor = ScrollSpy
【5】Anti-conflict processing

  $.fn.scrollspy.noConflict = function () {     //恢复以前的旧代码$.fn.scrollspy = old//将$.fn.scrollspy.noConflict()设置为Bootstrap的Scrollspy插件return this
  }
【6】Binding trigger event

  $(window).on('load.bs.scrollspy.data-api', function () {//遍历所有符合条件的滚动容器$('[data-spy="scroll"]').each(function () {      var $spy = $(this)      //执行scrollspy插件,并传入滚动容器上设置的自定义参数(data-开头)      Plugin.call($spy, $spy.data())
    })
  })

The above is the detailed content of Implementation of scroll monitor function in Bootstrap. For more information, please follow other related articles on the PHP Chinese website!

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 Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools