锚点之间的垂直和水平平滑滚动

both vertical and horizontal smooth scrolling between anchors

本文关键字:水平 平滑 滚动 垂直 之间      更新时间:2023-09-26

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

$(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 );
}
});
});

你也应该对 scrollLeft 属性进行动画处理...

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

或者使用 jquery scrollTo 插件。