簡體   English   中英

平滑滾動到 div id jQuery

[英]Smooth scroll to div id jQuery

我一直在嘗試滾動到 div id jquery 代碼以正常工作。 基於另一個堆棧溢出問題,我嘗試了以下

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);
});

但它沒有用。 它只是捕捉到 div。 我也試過

$('#myButton').click(function(event) {
     event.preventDefault();
   $.scrollTo($('#myDiv'), 1000);
});

毫無進展。

您需要為html, body設置動畫

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

如果要覆蓋頁面上的標准href-id 導航而不更改 HTML 標記以實現平滑滾動,請使用此(示例):

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

這是我的 2 美分:

Javascript:

$('.scroll').click(function() {
    $('body').animate({
        scrollTop: eval($('#' + $(this).attr('target')).offset().top - 70)
    }, 1000);
});

網址:

<a class="scroll" target="contact">Contact</a>

和目標:

<h2 id="contact">Contact</h2>

再舉一個例子:

HTML鏈接:

<a href="#featured" class="scrollTo">Learn More</a>

JS:

  $(".scrollTo").on('click', function(e) {
     e.preventDefault();
     var target = $(this).attr('href');
     $('html, body').animate({
       scrollTop: ($(target).offset().top)
     }, 2000);
  });

HTML 錨點:

  <div id="featured">My content here</div>

普通JS:

如果您使用現代瀏覽器,則可以在純 JS 中完成。

document
    .getElementById("range-calculator")
    .scrollIntoView({ behavior: "smooth" });

瀏覽器支持有點問題,但現代瀏覽器支持它

這是我使用的:

<!-- jquery smooth scroll to id's -->   
<script>
$(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
        }, 500);
        return false;
      }
    }
  });
});
</script>

這樣做的好處是您可以使用無限數量的哈希鏈接和相應的 ID,而無需為每個鏈接執行新腳本。

如果您使用的是 WordPress,請將代碼插入主題的footer.php文件中, footer.php正文結束標記</body>

如果您無權訪問主題文件,您可以將代碼嵌入帖子/頁面編輯器中(您必須在文本模式下編輯帖子)或將在所有頁面上加載的文本小部件。

如果您正在使用任何其他 CMS 或僅使用 HTML,您可以將代碼插入到所有頁面都在關閉正文標記</body>之前加載的部分中。

如果您需要更多詳細信息,請在此處查看我的快速帖子: jQuery smooth scroll to id

希望有所幫助,如果您對此有任何疑問,請告訴我。

此代碼對於網絡上的任何內部鏈接都很有用

    $("[href^='#']").click(function() {
        id=$(this).attr("href")
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 2000);
    });

您確定要加載 jQuery scrollTo 插件文件嗎?

您可能會在控制台中收到一個 object: method not found "scrollTo" 錯誤。

scrollTO 方法不是原生 jquery 方法。 要使用它,您需要包含 jquery scroll To 插件文件。

參考: http : //flesler.blogspot.in/2009/05/jqueryscrollto-142-released.html http://flesler.blogspot.in/2007/10/jqueryscrollto.html

soln:在 head 部分添加這個。

<script src="\\path\to\the\jquery.scrollTo.js file"></script>

該腳本是對 Vector 腳本的改進。 我對它做了一點改動。 所以這個腳本適用於每個包含類頁面滾動的鏈接。

起初沒有緩和:

$("a.page-scroll").click(function() {
    var targetDiv = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(targetDiv).offset().top
    }, 1000);
});

為方便起見,您將需要 Jquery UI:

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

將此添加到腳本中:

'easeOutExpo'

決賽

$("a.page-scroll").click(function() {
    var targetDiv = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(targetDiv).offset().top
    }, 1000, 'easeOutExpo');
});

您可以在此處找到所有緩動:備忘單

這是最簡單的。來源- https://www.w3schools.com/jsref/met_element_scrollintoview.asp

var elmnt = document.getElementById("content");
elmnt.scrollIntoView();

您可以使用以下簡單的 jQuery 代碼來實現。

可以從這里找到教程、演示和源代碼 -使用 jQuery 平滑滾動到 div

JavaScript:

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
        if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    });
});

HTML:

<a href="#section1">Go Section 1</a>
<div id="section1">
    <!-- Content goes here -->
</div>

我在這里嘗試了這個,這對我很有用。

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

    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 500, 'linear');
});

HTML:

 <a href="#fast-food" class="active" data-toggle="tab" >FAST FOOD</a>

<div id="fast-food">
<p> Scroll Here... </p>
  </div>

這是我使用 jQuery 平滑滾動到 div/anchor 的解決方案,以防您有一個固定的標題,這樣它就不會在它下面滾動。 如果您從其他頁面鏈接它,它也可以工作。

只需將“.site-header”替換為包含您的標題的 div。

$(function() {

$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
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 - headerheight)
    }, 1000);
    return false;
  }
}
});

//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
  var target = $('#'+location.href.split("#")[1]);
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - headerheight
    }, 1);
    return false;
  }
}
});

這對我有用。

<div id="demo">
        <h2>Demo</h2>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        // Handler for .ready() called.
        $('html, body').animate({
            scrollTop: $('#demo').offset().top
        }, 'slow');
    });
</script>

謝謝。

我對 Vanilla JS 和 jQuery 的解決方案

香草JS:

document
    .querySelector("#myDiv")
    .scrollIntoView({ behavior: "smooth" });

jQuery:

您需要為 html、body 設置動畫

$("#myButton").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

問題是JQuery。最簡單的應該在代碼下面。 確保包含 JQueryUI。 將 {version} 替換為最新版本,當然這里是您可以用於 animation 的所有方法的列表。2 秒的 easeOutExpo 會給您非常有藝術感的滾動。

線性,swing,easeOutQuad,easeInQuad,easeInOutQuad,easeOutCubic,easeInCubic,easeInOutCubic,easeOutQuart,easeInQuart,easeInOutQuart,easeOutQuint,easeInQuint,easeInOutQunit, easeOutExpo ,easeInExpo,easeInOutExpo,easeOutSine,easeInSine,easeInOutSine,easeOutElastic,easeInCirc,easeInCirc easeInOutElastic,easeOutBack,easeInBack,easeInOutBack,easeOutBounce,easeInBounce,easeInOutBounce

<script src="https://code.jquery.com/ui/{version}/jquery-ui.js"></script>

$('html, body').animate({ scrollTop: $("#id").offset().top }, 1000, "easeInExpo");

暫無
暫無

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

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