{"id":15030904,"url":"https://github.com/kswedberg/jquery-smooth-scroll","last_synced_at":"2025-05-13T17:13:32.116Z","repository":{"id":670242,"uuid":"313542","full_name":"kswedberg/jquery-smooth-scroll","owner":"kswedberg","description":"Automatically make same-page links scroll smoothly","archived":false,"fork":false,"pushed_at":"2024-12-10T14:41:52.000Z","size":824,"stargazers_count":1964,"open_issues_count":10,"forks_count":424,"subscribers_count":88,"default_branch":"master","last_synced_at":"2025-05-02T03:03:39.340Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kswedberg.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE-MIT","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-09-21T19:55:10.000Z","updated_at":"2025-04-02T23:12:23.000Z","dependencies_parsed_at":"2024-01-21T02:43:36.322Z","dependency_job_id":"55d1947e-4689-4ba6-86e4-ae936dc60e84","html_url":"https://github.com/kswedberg/jquery-smooth-scroll","commit_stats":{"total_commits":150,"total_committers":11,"mean_commits":"13.636363636363637","dds":"0.16000000000000003","last_synced_commit":"5c999995e05735435f43cda7db7eb8b33b2afaae"},"previous_names":[],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kswedberg%2Fjquery-smooth-scroll","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kswedberg%2Fjquery-smooth-scroll/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kswedberg%2Fjquery-smooth-scroll/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kswedberg%2Fjquery-smooth-scroll/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kswedberg","download_url":"https://codeload.github.com/kswedberg/jquery-smooth-scroll/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253354798,"owners_count":21895464,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-09-24T20:14:30.297Z","updated_at":"2025-05-13T17:13:27.104Z","avatar_url":"https://github.com/kswedberg.png","language":"JavaScript","funding_links":[],"categories":["13. 页面交互"],"sub_categories":["13.11 平滑滚动插件(Smooth Scroll) ###","13.11 平滑滚动插件(Smooth Scroll)"],"readme":"# Smooth Scroll Plugin\n\nAllows for easy implementation of smooth scrolling for same-page links.\n\n[![NPM](https://nodei.co/npm/jquery-smooth-scroll.png?compact=true)](https://npmjs.org/package/jquery-smooth-scroll)\n\nNote: Version 2.0+ of this plugin requires jQuery version 1.7 or greater.\n\n## Setup\n\n### ES Module\n\n```bash\nnpm install jquery-smooth-scroll\n```\n\nor\n\n```bash\nyarn add jquery-smooth-scroll\n```\n\nThen, use `import jquery-smooth-scroll`;\n\n**Note**: This assumes `window.jQuery` is available at time of import.\n\n### CDN\n\n```html\n\u003c!--\n  You can get a URL for jQuery from\n  https://code.jquery.com\n--\u003e\n\u003cscript src=\"SOME_URL_FOR_JQUERY\"\u003e\u003c/script\u003e\n\u003cscript src=\"https://cdn.statically.io/gh/kswedberg/jquery-smooth-scroll/3948290d/jquery.smooth-scroll.min.js\"\u003e\u003c/script\u003e\n```\n\n### Copy/paste\n\nGrab the code and paste it into your own file:\n\n* [Standard version](https://raw.githubusercontent.com/kswedberg/jquery-smooth-scroll/master/jquery.smooth-scroll.js)\n* [Minified version](https://raw.githubusercontent.com/kswedberg/jquery-smooth-scroll/master/jquery.smooth-scroll.js)\n\n## Demo\n\nYou can try a bare-bones demo at [kswedberg.github.io/jquery-smooth-scroll/demo/](https://kswedberg.github.io/jquery-smooth-scroll/demo/)\n\n## Features\n\n### $.fn.smoothScroll\n\n* Works like this: `$('a').smoothScroll();`\n* Specify a containing element if you want: `$('#container a').smoothScroll();`\n* Exclude links if they are within a containing element: `$('#container a').smoothScroll({excludeWithin: ['.container2']});`\n* Exclude links if they match certain conditions: `$('a').smoothScroll({exclude: ['.rough','#chunky']});`\n* Adjust where the scrolling stops: `$('.backtotop').smoothScroll({offset: -100});`\n* Add a callback function that is triggered before the scroll starts: `$('a').smoothScroll({beforeScroll: function() { alert('ready to go!'); }});`\n* Add a callback function that is triggered after the scroll is complete: `$('a').smoothScroll({afterScroll: function() { alert('we made it!'); }});`\n* Add back button support by using a [`hashchange` event listener](https://developer.mozilla.org/en-US/docs/Web/API/HashChangeEvent). You can also include a history management plugin such as [Ben Alman's BBQ](http://benalman.com/code/projects/jquery-bbq/docs/files/jquery-ba-bbq-js.html) for ancient browser support (IE \u0026lt; 8), but you'll need jQuery 1.8 or earlier. See [demo/hashchange.html](demo/hashchange.html) or [demo/bbq.html](demo/bbq.html) for an example of how to implement.\n\n#### Options\n\nThe following options, shown with their default values, are available for both `$.fn.smoothScroll` and `$.smoothScroll`:\n\n```javascript\n{\n  offset: 0,\n\n  // one of 'top' or 'left'\n  direction: 'top',\n\n  // only use if you want to override default behavior or if using $.smoothScroll\n  scrollTarget: null,\n\n  // automatically focus the target element after scrolling to it\n  // (see https://github.com/kswedberg/jquery-smooth-scroll#focus-element-after-scrolling-to-it for details)\n  autoFocus: false,\n\n  // string to use as selector for event delegation\n  delegateSelector: null,\n\n  // fn(opts) function to be called before scrolling occurs.\n  // `this` is the element(s) being scrolled\n  beforeScroll: function() {},\n\n  // fn(opts) function to be called after scrolling occurs.\n  // `this` is the triggering element\n  afterScroll: function() {},\n\n  // easing name. jQuery comes with \"swing\" and \"linear.\" For others, you'll need an easing plugin\n  // from jQuery UI or elsewhere\n  easing: 'swing',\n\n  // speed can be a number or 'auto'\n  // if 'auto', the speed will be calculated based on the formula:\n  // (current scroll position - target scroll position) / autoCoefficient\n  speed: 400,\n\n  // autoCoefficent: Only used when speed set to \"auto\".\n  // The higher this number, the faster the scroll speed\n  autoCoefficient: 2,\n\n  // $.fn.smoothScroll only: whether to prevent the default click action\n  preventDefault: true\n\n}\n```\n\nThe options object for `$.fn.smoothScroll` can take two additional properties:\n`exclude` and `excludeWithin`. The value for both of these is an array of\nselectors, DOM elements or jQuery objects. Default value for both is an\nempty array.\n\n#### Setting options after initial call\n\nIf you need to change any of the options after you've already called `.smoothScroll()`,\nyou can do so by passing the `\"options\"` string as the first argument and an\noptions object as the second.\n\n### $.smoothScroll\n\n* Utility method works without a selector: `$.smoothScroll()`\n* Can be used to scroll any element (not just `document.documentElement` / `document.body`)\n* Doesn't automatically fire, so you need to bind it to some other user\n  interaction. For example:\n\n  ```js\n  $('button.scrollsomething').on('click', function() {\n    $.smoothScroll({\n      scrollElement: $('div.scrollme'),\n      scrollTarget: '#findme'\n    });\n    return false;\n  });\n  ```\n\n* The `$.smoothScroll` method can take one or two arguments.\n  * If the first argument is a number or a \"relative string,\" the document is scrolled to that\n    position. If it's an options object, those options determine how the\n    document (or other element) will be scrolled.\n  * If a number or \"relative string\" is provided as the second argument, it will override whatever may have been set for the `scrollTarget` option.\n  * The relative string syntax, introduced in version 2.1, looks like `\"+=100px\"` or `\"-=50px\"` (see below for an example).\n\n#### Additional Option\n\nThe following option, in addition to those listed for `$.fn.smoothScroll` above, is available\nfor `$.smoothScroll`:\n\n```javascript\n{\n  // The jQuery set of elements you wish to scroll.\n  //  if null (default), $('html, body').firstScrollable() is used.\n  scrollElement: null\n}\n```\n\n#### Note:\n\nIf 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.\n\n### $.fn.scrollable\n\n* Selects the matched element(s) that are scrollable. Acts just like a\n  DOM traversal method such as `.find()` or `.next()`.\n* Uses `document.scrollingElement` on compatible browsers when the selector is 'html' or 'body' or 'html, body'.\n* The resulting jQuery set may consist of **zero, one, or multiple**\n  elements.\n\n### $.fn.firstScrollable\n\n* Selects the first matched element that is scrollable. Acts just like a\n  DOM traversal method such as `.find()` or `.next()`.\n* The resulting jQuery set may consist of **zero or one** element.\n* This method is used *internally* by the plugin to determine which element\n  to use for \"document\" scrolling:\n  `$('html, body').firstScrollable().animate({scrollTop: someNumber},\n  someSpeed)`\n* Uses `document.scrollingElement` on compatible browsers when the selector is 'html' or 'body' or 'html, body'.\n\n## Examples\n\n### Scroll down one \"page\" at a time (v2.1+)\n\nWith 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:\n\n  ```js\n  $('button.pagedown').on('click', function() {\n    $.smoothScroll('+=' + $(window).height());\n  });\n  ```\n\n### Smooth scrolling on page load\n\nIf 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()`.\n\nFor example, let's say you want to smooth scroll to `\u003cdiv id=\"scrolltome\"\u003e\u003c/div\u003e` on page-2.html. For page-1.html, your script might do the following:\n\n```js\n$('a[href=\"page-2.html#scrolltome\"]').attr('href', function() {\n  var hrefParts = this.href.split(/#/);\n  hrefParts[1] = 'smoothScroll' + hrefParts[1];\n  return hrefParts.join('#');\n});\n\n```\n\nThen for page-2.html, your script would do this:\n\n```js\n// Call $.smoothScroll if location.hash starts with \"#smoothScroll\"\nvar reSmooth = /^#smoothScroll/;\nvar id;\nif (reSmooth.test(location.hash)) {\n  // Strip the \"#smoothScroll\" part off (and put \"#\" back on the beginning)\n  id = '#' + location.hash.replace(reSmooth, '');\n  $.smoothScroll({scrollTarget: id});\n}\n```\n\n### Focus element after scrolling to it.\n\nImagine 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.\n\n* As of **smoothScroll version 2.2**, the plugin will automatically focus the element if you set the `autoFocus` option to `true`.\n\n    ```js\n    $('div.example').smoothScroll({\n      autoFocus: true\n    });\n    ```\n\n* In the future, versions 3.x and later will have `autoFocus` set to true **by default**.\n* If you are using the low-level `$.smoothScroll` method, `autoFocus` will only work if you've also provided a value for the `scrollTarget` option.\n* 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:\n\n```js\n$('a.example').smoothScroll({\n  afterScroll: function(options) {\n    $(options.scrollTarget).find('input')[0].focus();\n  }\n});\n\n```\n\nFor 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):\n\n```js\n$('div.example').smoothScroll({\n  afterScroll: function(options) {\n    var $tgt = $(options.scrollTarget);\n    $tgt[0].focus();\n\n    if (!$tgt.is(document.activeElement)) {\n      $tgt.attr('tabIndex', '-1');\n      $tgt[0].focus();\n    }\n  }\n});\n```\n\n## Notes\n\n* To determine where to scroll the page, the `$.fn.smoothScroll` method looks\nfor an element with an _id_ attribute that matches the `\u003ca\u003e` element's hash.\nIt does _not_ look at the element's _name_ attribute. If you want a clicked link\nto scroll to a \"named anchor\" (e.g. `\u003ca name=\"foo\"\u003e`), you'll need to use the\n`$.smoothScroll` method instead.\n* The plugin's `$.fn.smoothScroll` and `$.smoothScroll` methods use the\n`$.fn.firstScrollable` DOM traversal method (also defined by this plugin)\nto determine which element is scrollable. If no elements are scrollable,\nthese methods return a jQuery object containing an empty array, just like\nall of jQuery's other DOM traversal methods. Any further chained methods,\ntherefore, will be called against no elements (which, in most cases,\nmeans that nothing will happen).\n\n## Contributing\n\nThank you! Please consider the following when working on this repo before you submit a pull request:\n\n* For code changes, please work on the \"source\" file: `src/jquery.smooth-scroll.js`.\n* Style conventions are noted in the `jshint` grunt file options and the `.jscsrc` file. To be sure your additions comply, run `grunt lint` from the command line.\n* If possible, please use Tim Pope's [git commit message style](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). Multiple commits in a pull request will be squashed into a single commit. I may adjust the message for clarity, style, or grammar. I manually commit all merged PRs using the `--author` flag to ensure that proper authorship (yours) is maintained.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkswedberg%2Fjquery-smooth-scroll","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkswedberg%2Fjquery-smooth-scroll","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkswedberg%2Fjquery-smooth-scroll/lists"}