簡體   English   中英

jQuery平滑滾動Onclick

[英]Jquery Smooth Scroll Onclick

我目前正在使用來自CSS技巧的平滑滾動腳本。

我遇到的問題是,我已經將的和用作與錨元素的onclick鏈接。

你可以在這里看到它。 問題在於腳本沒有找到我需要的內容,腳本未找到頂部的鏈接(div),因此無法平滑滾動至錨點。 而About,Service,Contact鏈接(綠色小物件中的文本鏈接)會平滑滾動。

我是完整的jquery和javascript noob,並且不知道如何更改腳本以包括onclick div或制作腳本以使其平滑滾動到錨點。

我需要該腳本從div鏈接和文本鏈接中平滑滾動,或者我需要一個可與div鏈接一起使用的重復腳本(2個執行文本鏈接和div鏈接的腳本-我正在使用的atm腳本僅執行文本操作)

<script>
$(document).ready(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}, 400, function() {
        location.hash = target;
      });
    });
     }
       }
  });

  // use the first element that is "scrollable"
  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 [];
  }

    });
</script>

我不知道您是否使用jQuery之類的JavaScript框架。 對於這樣的網站,我總是使用jQuery插件“ Localscroll”。 跨瀏覽器始終有效。

您可以在此處查看該插件的文檔: http : //flesler.blogspot.com/2007/10/jquerylocalscroll-10.html

它很容易使用。

祝好運!

您現在可以在導航欄中使用錨點而不是div。

<div id="whatever" onclick="window.location=#portfolio">portfolio</div>

但這不是語義的,並且不能按您希望的方式工作,因此doubleplus不好。 采用

<a id="whatever" href="#portfolio" style="display:block">portfolio</a>

那么css技巧中的代碼應該可以工作...如果可以單擊,則可能應該是按鈕或錨點。

人體中的錨標簽會按預期工作,但...

暫無
暫無

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

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