簡體   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