簡體   English   中英

jquery順利滾動到錨點?

[英]jquery smooth scroll to an anchor?

有沒有辦法使用jQuery向下滾動到錨鏈接?

喜歡:

$(document).ready(function(){
  $("#gotomyanchor").click(function(){
      $.scrollSmoothTo($("#myanchor"));
  });
});

我是這樣做的:

    var hashTagActive = "";
    $(".scroll").on("click touchstart" , function (event) {
        if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
            event.preventDefault();
            //calculate destination place
            var dest = 0;
            if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
                dest = $(document).height() - $(window).height();
            } else {
                dest = $(this.hash).offset().top;
            }
            //go to destination
            $('html,body').animate({
                scrollTop: dest
            }, 2000, 'swing');
            hashTagActive = this.hash;
        }
    });

然后你只需要像這樣創建你的錨:

<a class="scroll" href="#destination1">Destination 1</a>

你可以在我的網站上看到它。
這里也有一個演示: http//jsfiddle.net/YtJcL/

我會使用CSS-Tricks.com的簡單代碼片段:

$(function() {
  $('a[href*=#]:not([href=#])').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) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

資料來源http//css-tricks.com/snippets/jquery/smooth-scrolling/

到目前為止我見過的最佳解決方案: jQuery:Smooth Scrolling Internal Anchor Links

HTML:

<a href="#comments" class="scroll">Scroll to comments</a>

腳本:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

jQuery.scrollTo會做你想要的一切,甚至更多!

你可以傳遞各種不同的東西:

  • 原始數字
  • 字符串('44','100px','+ = 30px'等)
  • DOM元素(邏輯上,可滾動元素的子元素)
  • 一個選擇器,它將相對於可滾動元素
  • 字符串'max'滾動到結尾。
  • 一個字符串,指定滾動到容器的該部分的百分比(fe:50%轉到*到中間)。
  • 哈希{top:x,left:y},x和y可以是任何類型的數字/字符串,如上所述。

這是我用來快速將jQuery scrollTo綁定到所有錨鏈接的代碼:

// Smooth scroll
$('a[href*=#]').click(function () {
    var hash = $(this).attr('href');
    hash = hash.slice(hash.indexOf('#') + 1);
    $.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
    window.location.hash = '#' + hash;
    return false;
});

我想要一個適用於<a href="#my-id"><a href="/page#my-id">

<script>        
    $('a[href*=#]:not([href=#])').on('click', function (event) {
        event.preventDefault();
        var element = $(this.hash);
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
    });
</script>

試試這個吧。 這是我修改的CSS技巧的代碼,它非常簡單,同時進行水平和垂直滾動。 需要JQuery。 這是一個演示

$(function() {
  $('a[href*=#]:not([href=#])').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) {
        $('html,body').animate({
          scrollTop: target.offset().top-10, scrollLeft:target.offset().left-10
        }, 1000);
        return false;
      }
    }
  });
});

使用hanoo的腳本我創建了一個jQuery函數:

$.fn.scrollIntoView = function(duration, easing) {
    var dest = 0;
    if (this.offset().top > $(document).height() - $(window).height()) {
        dest = $(document).height() - $(window).height();
    } else {
        dest = this.offset().top;
    }
    $('html,body').animate({
        scrollTop: dest
    }, duration, easing);
    return this;
};

用法:

$('#myelement').scrollIntoView();

持續時間和寬松的默認值是400毫秒和“擺動”。

我在我的網站上使用了這個:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 1200, 'swing', function () {
        window.location.hash = target;
    });
});

});

您可以更改滾動的速度,更改我默認使用的“1200”,它在大多數瀏覽器上運行得相當好。

將代碼放在頁面的<head> </head>標記之后,您需要在<body>標記中創建內部鏈接:

<a href="#home">Go to Home</a>

希望能幫助到你!

Ps:別忘了打電話:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

我在http://plugins.jquery.com/smooth-scroll/上使用了插件Smooth Scroll 使用此插件,您需要包含的是jQuery和插件代碼的鏈接:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>

(鏈接需要使用smoothScroll類才能工作)。

Smooth Scroll的另一個功能是ancor名稱不會顯示在URL中!

作品

$('a[href*=#]').each(function () {
    $(this).attr('href', $(this).attr('href').replace('#', '#_'));
    $(this).on( "click", function() {

        var hashname = $(this).attr('href').replace('#_', '');

        if($(this).attr('href') == "#_") {
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
        else {
            var target = $('a[name="' + hashname + '"], #' + hashname),
                targetOffset = target.offset().top;
            if(targetOffset >= 1) {
                $('html, body').animate({ scrollTop: targetOffset-60 }, 300);
            }
        }
    });
});

我討厭在我的代碼中添加函數命名的類,所以我把它放在一起。 如果我要停止使用平滑滾動,我會覺得有必要通過我的代碼,並刪除所有class =“scroll”的東西。 使用這種技術,我可以評論5行JS,整個站點更新。 :)

<a href="/about">Smooth</a><!-- will never trigger the function -->
<a href="#contact">Smooth</a><!-- but he will -->
...
...
<div id="contact">...</div>


<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    // Smooth scrolling to element IDs
    $('a[href^=#]:not([href=#])').on('click', function () {
        var element = $($(this).attr('href'));
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
        return false;
    });
</script>

要求
1. <a>元素必須有一個以#開頭的href屬性,而不僅僅是#
2.頁面上具有匹配id屬性的元素

它能做什么:
1.該函數使用href值來創建anchorID對象
- 在示例中,它是$('#contact')/about/開頭
2. HTMLBODY被動畫anchorID的頂部偏移量
- speed ='normal'('fast','slow',毫秒,)
- 寬松='搖擺'('線性'等...谷歌寬松)
3. return false - 它阻止瀏覽器在URL中顯示哈希值
- 腳本在沒有它的情況下工作,但它並不像“ 平滑 ”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM