jquery-smooth-scroll 页面平滑滚动 jQuery 插件

页面内导航常见于百科类网站,或者是文章的内容很多的时候,我们需要一个平滑滚动的效果来缓解突然跳转的尴尬,jquery-smooth-scroll 就是这样一款平滑滚动的 jQuery 插件。

jquery-smooth-scroll 页面平滑滚动 jQuery 插件

使用步骤

1、引入以下的 js 和 css 文件

<script src="jquery.min.js"></script>

<script src="jquery.smooth-scroll.js"></script>

<script src="jquery.ba-bbq.js"></script>

2、在 head 标签中加入以下js代码

$(function(){

$("#btn").click(function(){

$('a').smoothScroll({

//参数列表

});

});

})

3、在body标签中加入相应的标签

插件说明

1、允许我们轻易地实现滑动到页面某个位置

2、可以这样来调用插件

$('a').smoothScroll();

3、可以根据自己的需要指定一个外部容器,那么滚动就是在这个容器内发生,而不是在页面级别发生了

$('#container a').smoothScroll();

4、可以通过下面的方式来排除指定容器的包含元素

$('#container a').smoothScroll({

excludeWithin: ['.container2']

});

5、通过下面的语句来排除满足指定条件的元素

$('a').smoothScroll({

exclude: ['.rough','#chunky']

});

6、调整滑动到哪个位置就停止

$('.backtotop').smoothScroll({

offset: -100

});

7、设定一个滑动开始之前的回调函数

$('a').smoothScroll({

beforeScroll: function() {

alert('ready to go!');

}

});

8、设定一个滑动结束的回调函数

$('a').smoothScroll({

afterScroll: function() {

alert('we made it!');

}

});

9、可以添加一个按钮用来支持点击后回到之前的位置,实际上就是一个历史记录的作用

参数配置

$.smoothScroll({

//滑动到的位置的偏移量

offset: 0,

//滑动的方向,可取 'top' 或 'left'

direction: 'top',

// 只有当你想重写默认行为的时候才会用到

scrollTarget: null,

// 滑动开始前的回调函数。`this` 代表正在被滚动的元素

beforeScroll: function() {},

//滑动完成后的回调函数。 `this` 代表触发滑动的元素

afterScroll: function() {},

//缓动效果

easing: 'swing',

//滑动的速度

speed: 400,

// "自动" 加速的系数

autoCoefficent: 2

});

选项对象 $.fn.smoothScroll 可以采用两个附加属性:excludeexcludeWithin。这两个值都是选择器、DOM 元素或 jQuery 对象的数组。两者的默认值都是空数组。

初始调用后设置选项

如果在调用 .smoothScroll() 之后需要更改任何选项,可以通过将 options 字符串作为第一个参数传递,将 options 对象作为第二个参数传递来完成此操作。

方法函数

$.smoothScroll

  • Utility method works without a selector: $.smoothScroll()
  • Can be used to scroll any element (not just document.documentElement / document.body)
  • Doesn’t automatically fire, so you need to bind it to some other user interaction. For example:

    $('button.scrollsomething').on('click', function() {

    $.smoothScroll({

    scrollElement: $('div.scrollme'),

    scrollTarget: '#findme'

    });

    return false;

    });

  • The $.smoothScroll method can take one or two arguments.

    • If the first argument is a number or a “relative string,” the document is scrolled to that position. If it’s an options object, those options determine how the document (or other element) will be scrolled.
    • If a number or “relative string” is provided as the second argument, it will override whatever may have been set for the scrollTarget option.
    • The relative string syntax, introduced in version 2.1, looks like "+=100px" or "-=50px" (see below for an example).

Additional Option

The following option, in addition to those listed for $.fn.smoothScroll above, is available for $.smoothScroll:

{

// The jQuery set of elements you wish to scroll.

// if null (default), $('html, body').firstScrollable() is used.

scrollElement: null

}

Note:

If you use $.smoothScroll, do NOT use the body element (document.body or $('body')) alone for the scrollElement option. Probably not a good idea to use document.documentElement ($('html')) by itself either.

$.fn.scrollable

  • Selects the matched element(s) that are scrollable. Acts just like a DOM traversal method such as .find() or .next().
  • Uses document.scrollingElement on compatible browsers when the selector is ‘html’ or ‘body’ or ‘html, body’.
  • The resulting jQuery set may consist of zero, one, or multiple elements.

$.fn.firstScrollable

  • Selects the first matched element that is scrollable. Acts just like a DOM traversal method such as .find() or .next().
  • The resulting jQuery set may consist of zero or one element.
  • This method is used internally by the plugin to determine which element to use for “document” scrolling: $('html, body').firstScrollable().animate({scrollTop: someNumber}, someSpeed)
  • Uses document.scrollingElement on compatible browsers when the selector is ‘html’ or ‘body’ or ‘html, body’.

Examples

Scroll down one “page” at a time (v2.1+)

With smoothScroll version 2.1 and later, you can use the “relative string” syntax to scroll an element or the document a certain number of pixels relative to its current position. The following code will scroll the document down one page at a time when the user clicks the “.pagedown” button:

$('button.pagedown').on('click', function() {

$.smoothScroll('+=' + $(window).height());

});

Smooth scrolling on page load

If you want to scroll to an element when the page loads, use $.smoothScroll() in a script at the end of the body or use $(document).ready(). To prevent the browser from automatically scrolling to the element on its own, your link on page 1 will need to include a fragment identifier that does not match an element id on page 2. To ensure that users without JavaScript get to the same element, you should modify the link’s hash on page 1 with JavaScript. Your script on page 2 will then modify it back to the correct one when you call $.smoothScroll().

For example, let’s say you want to smooth scroll to <div id="scrolltome"></div> on page-2.html. For page-1.html, your script might do the following:

$('a[href="page-2.html#scrolltome"]').attr('href', function() {

var hrefParts = this.href.split(/#/);

hrefParts[1] = 'smoothScroll' + hrefParts[1];

return hrefParts.join('#');

});

Then for page-2.html, your script would do this:

// Call $.smoothScroll if location.hash starts with "#smoothScroll"

var reSmooth = /^#smoothScroll/;

var id;

if (reSmooth.test(location.hash)) {

// Strip the "#smoothScroll" part off (and put "#" back on the beginning)

id = '#' + location.hash.replace(reSmooth, '');

$.smoothScroll({scrollTarget: id});

}

Focus element after scrolling to it.

Imagine you have a link to a form somewhere on the same page. When the user clicks the link, you want the user to be able to begin interacting with that form.

  • As of smoothScroll version 2.2, the plugin will automatically focus the element if you set the autoFocus option to true.

    $('div.example').smoothScroll({

    autoFocus: true

    });

  • In the future, versions 3.x and later will have autoFocus set to true by default.
  • If you are using the low-level $.smoothScroll method, autoFocus will only work if you’ve also provided a value for the scrollTarget option.
  • Prior to version 2.2, you can use the afterScroll callback function. Here is an example that focuses the first input within the form after scrolling to the form:

$('a.example').smoothScroll({

afterScroll: function(options) {

$(options.scrollTarget).find('input')[0].focus();

}

});

For accessibility reasons, it might make sense to focus any element you scroll to, even if it’s not a natively focusable element. To do so, you could add a tabIndex attribute to the target element (this, again, is for versions prior to 2.2):

$('div.example').smoothScroll({

afterScroll: function(options) {

var $tgt = $(options.scrollTarget);

$tgt[0].focus();

if (!$tgt.is(document.activeElement)) {

$tgt.attr('tabIndex', '-1');

$tgt[0].focus();

}

}

});

Notes

  • To determine where to scroll the page, the $.fn.smoothScroll method looks for an element with an id attribute that matches the <a> element’s hash. It does not look at the element’s name attribute. If you want a clicked link to scroll to a “named anchor” (e.g. <a name="foo">), you’ll need to use the $.smoothScroll method instead.
  • The plugin’s $.fn.smoothScroll and $.smoothScroll methods use the $.fn.firstScrollable DOM traversal method (also defined by this plugin) to determine which element is scrollable. If no elements are scrollable, these methods return a jQuery object containing an empty array, just like all of jQuery’s other DOM traversal methods. Any further chained methods, therefore, will be called against no elements (which, in most cases, means that nothing will happen).

相关链接

  • https://github.com/kswedberg/jquery-smooth-scroll
  • https://www.npmjs.com/package/jquery-smooth-scroll

以上是 jquery-smooth-scroll 页面平滑滚动 jQuery 插件 的全部内容, 来源链接: utcz.com/p/232597.html

回到顶部