简体   繁体   中英

Delay scrolling to anchor link

I am terrible with JS and possibly even worse at explaining what I'm doing so please bear with me. I have an external script that smooths the transitions on scrolling to anchor links. I want to delay the scroll on just one element.

External Script:

$(function() {

        function filterPath(string) {
            return string
            .replace(/^\//,'')
            .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
            .replace(/\/$/,'');
        }

        var locationPath = filterPath(location.pathname);
        var scrollElem = scrollableElement('html', 'body');
                $('a[href*=#]').each(function() {
                var thisPath = filterPath(this.pathname) || locationPath;
                if (  locationPath == thisPath  && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) {
                var $target = $(this.hash), target = this.hash;
                if (target) {
                var targetOffset = $target.offset().top;
                $(this).click(function(event) {
                event.preventDefault();
                $(scrollElem).animate({scrollTop: targetOffset}, 2600, function() {

                location.hash = target;
            });});}}}); 

                function scrollableElement(els) {
            for (var i = 0, argLength = arguments.length; i <argLength; i++) {
                var el = arguments[i],
                $scrollElement = $(el); 
                if ($scrollElement.scrollTop()> 0) {
                    return el;
                } else {
                    $scrollElement.scrollTop(1);
                    var isScrollable = $scrollElement.scrollTop()> 0;
                    $scrollElement.scrollTop(0);
                    if (isScrollable) {
                        return el;
                    }}}return [];}});

It is embedded in the main php file like so:

<script src="smoothScroll.js"></script>

So this is totally wrong but what i want to do essentially:

<a href="#whatwedo" onClick="setTimeout(smoothScroll.js, 5000)">

What would be the best way of delaying the scroll for just this one element?

I guess you could match a specific anchor value from the href statically, even though it's sloppy.

https://jsfiddle.net/cpcnsd0v/

var delay;

$('a').click(function(e) {
    e.preventDefault();
    delay = 0;

    if ($(this).attr('href').split('#')[1] === 'whatwedo') {
        delay = 1000;
    }

    setTimeout(function() {
        // do scroll here
    },delay);
});

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