简体   繁体   中英

How to add smooth scrolling to all in page anchor links

Trying to write a script to add smooth scrolling for all links that resolve to an anchor on the current page. Trying to make this generic so it works site-wide.

var links = document.querySelectorAll('a')
var anchorLinks = []

for (var i = 0; i < links.length; i += 1) {
  console.log(links[i].href, window.location.href)
}

That's my start, but I'm running into challenges, and I'm reaching out on Stackoverflow to see if anyone's done this without jQuery.

I have to check if the href has a # , but I also have to check if the current URL matches the href, because other sites use # 's too.

Would that do it? Or am I missing something else?

To sum up, see Location object .

Try this:

var links = document.querySelectorAll('a')
var anchorLinks = [].filter.call(links,a=>(
  a.host==window.location.host&&
  a.pathname==window.location.pathname&&
  a.search==window.location.search&&
  a.hash!=window.location.hash))

There is actually another way to do that:

var locwohash = window.location.href.replace(/#.+/, "")
var anchorLinks = document.querySelectorAll('a[href^="'+locwohash+'"],a[href^="#"]')

Should be faster, but will be complex if wanting to be robust to different types of link hrefs. (for http://example.com/path/to/page#hash , there are many hrefs to link to anchor in this page, #another-hash , page#another-hash , example.com/path/to/page#another-hash , /path/to/page#another-hash , //example.com/path/to/page#another-hash , http://example.com/path/to/page#another-hash , all of these are equivalent but not identical by selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM