【问题标题】:both vertical and horizontal smooth scrolling between anchors锚点之间的垂直和水平平滑滚动
【发布时间】:2014-04-06 20:18:03
【问题描述】:

我想在同一页面上使用锚点进行平滑滚动。 我所有的锚点都分布在不同水平或/和垂直水平的页面上。 我在下面得到了这段代码,它只适用于垂直滚动,不适用于水平滚动。 我应该怎么做才能使滚动同时垂直和水平?

$(function() {

// scroll handler
var scrollToAnchor = function( id ) {

// grab the element to scroll to based on the name
var elem = $("a[name='"+ id +"']");

// if that didn't work, look for an element with our ID
if ( typeof( elem.offset() ) === "undefined" ) {
  elem = $("#"+id);
}

// if the destination element exists
if ( typeof( elem.offset() ) !== "undefined" ) {

  // do the scroll
  $('html, body').animate({
          scrollTop: elem.offset().top
  }, 1000 );

}
};

// bind to click event
$("a").click(function( event ) {

// only do this if it's an anchor link
if ( $(this).attr("href").match("#") ) {

  // cancel default event propagation
  event.preventDefault();

  // scroll to the location
  var href = $(this).attr('href').replace('#', '')
  scrollToAnchor( href );

}

});

});

【问题讨论】:

    标签: javascript html scroll smoothing


    【解决方案1】:

    您还应该为 scrollLeft 属性设置动画...

    $('html, body').animate({
              scrollTop: elem.offset().top,
              scrollLeft: elem.offset().left
    }, 1000 );
    

    或者使用 jquery scrollTo 插件。

    【讨论】:

    • 啊,是的,我搞砸了:我的代码中有一个错字要添加左侧,这就是它不起作用的原因。是的,我也在看 scrollTo 插件。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多