首页 > 语言 > JavaScript > 正文

Bootstrap每天必学之滚动监听

2024-05-06 15:00:09
字体:
来源:转载
供稿:网友

本文为大家介绍Bootstrap滚动监听,供大家学习,具体内容如下

1. Scrollspy currently requires the use of a Bootstrap nav component for proper highlighting of active links.

---- 使用滚动监听的话,导航栏必须采用 class="nav"的nav组件才可以:

下面是源代码中的一段,标红的部分可以证明这一点:

使用ScrollSpy的时候,需要采用<ul class="nav">标签,并且在<li>下必须有<a>标签。

注:另外我们需要把<ul class="nav">标签放到另一个容器内(如div),并给父容器添加一个id属性(这一点在第4节有介绍)

function ScrollSpy(element, options) { this.$body   = $(document.body) this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) this.options  = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector  = (this.options.target || '') + ' .nav li > a' this.offsets  = [] this.targets  = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) this.refresh() this.process() }

2. Navbar links must have resolvable id targets. For example, a <a href="#home">home</a> must correspond to something in the DOM like <div id="home"></div>.

--- 简单的说,就是<li>下的<a>标签必须有一个href="#id"属性,并且在滚动的内容里面,必须有对应的<a id="id"></a>这样的标签;当内容滚动到<a id="id">标签时,对应的<li>的<a href="#id">就会自动被选中。

--其实这一点做过Web开发的朋友都知道,在之前的HTML版本中,锚标记 通常采用<a name="tag">这样的方式,但HTML5中的锚标记已经抛弃了name属性,而是采用id属性

 ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector +  '[data-target="' + target + '"],' +  this.selector + '[href="' + target + '"]' var active = $(selector)  .parents('li')  .addClass('active') if (active.parent('.dropdown-menu').length) {  active = active  .closest('li.dropdown')  .addClass('active') } active.trigger('activate.bs.scrollspy') }

3. No matter the implementation method, scrollspy requires the use of position: relative; on the element you're spying on. In most cases this is the <body>. When scrollspying on elements other than the <body>, be sure to have a height set and overflow-y: scroll; applied.

--- 如果监听Body的滚动,那么你必须给body添加position:relative样式

--- 如果监听的不是Body,而是其他得元素[貌似这种方式常见],那么你需要添加三个样式:position:relative;height:500px;overflow-y:scroll;

ScrollSpy.prototype.refresh = function () { var that   = this var offsetMethod = 'offset' var offsetBase = 0 this.offsets  = [] this.targets  = [] this.scrollHeight = this.getScrollHeight() if (!$.isWindow(this.$scrollElement[0])) {  offsetMethod = 'position'  offsetBase = this.$scrollElement.scrollTop() }            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选