繁体   English   中英

平滑滚动特定的锚链接

[英]Smooth Scrolling for specific anchor links

我正在使用Google的平滑滚动脚本来处理特定的锚链接#tothetop而不是仅使用任何# 我在example.js文件中做了这个(你用脚本下载):

更改:

$('a[href*=#]').click(function() { ... });

至:

$('a[href*=#tothetop]').click(function() { ... });

所以现在它只将平滑滚动应用到#tothetop ,但我如何将它应用于其他不同的锚链接? 例如: #tothetop#tothebottom#gotothepub等? (不要问为什么我没有使用'#',因为这是一个很长的故事,但简而言之 - 它与页面上的另一个脚本冲突)我试过:

$('a[href*=#tothetop]','a[href*=#tothebottom]').click(function() { ... });

但这不起作用。 我对Javascript和PHP知之甚少,但我确信有一个简单的方法可以做到这一点?

example.js的完整代码如下:

$(function(){

$('a[href*=#tothetop]').click(function() {

if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    && location.hostname == this.hostname) {

        var $target = $(this.hash);

        $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');

        if ($target.length) {

            var targetOffset = $target.offset().top;

            $('html,body').animate({scrollTop: targetOffset}, 1000);

            return false;

        }

    }

});

});

尝试

$('a[href^="#"]').click(...);

此选择器将匹配href属性以#开头的所有锚点。

你的例子是有效的,但应该这样写

$('a[href*="#tothetop"], a[href*="#tothebottom"]')

请注意值和单引号周围的引号(仅使用一次)。

我会使用它,因为显然你用“toTheAnchor”命名你的滚动锚点:

$('body').on('click', 'a[href^=#][href*=to]', function() {});

这应该选择以“#”开头的所有链接,并在单词中包含“to”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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