单击锚链接时平滑滚动

时间:2011-10-10 19:19:35

标签: javascript jquery scroll hyperlink anchor

我的页面上有几个超链接。用户在访问我的帮助部分时会阅读的常见问题解答。

使用锚点链接,我可以使页面滚动到锚点并引导用户。

有没有办法让滚动顺畅?

但请注意他正在使用自定义JavaScript库。也许jQuery提供这样的东西?

28 个答案:

答案 0 :(得分:1013)

更新2018年4月:现在有a native way to do this

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

目前仅在最前沿的浏览器中支持此功能。


对于较旧的浏览器支持,您可以使用此jQuery技术:

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

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

这是小提琴:http://jsfiddle.net/9SDLw/


如果您的目标元素没有ID,并且您通过其name链接到该ID,请使用:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);

    return false;
});

为了提高性能,您应该缓存该$('html, body')选择器,以便它不会每次单击

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});

如果您希望更新网址,请在animate回调中执行此操作:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});

答案 1 :(得分:153)

正确的语法是:

//Smooth scrolling with links
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});

// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
  $('html,body').animate({scrollTop:$(location.hash).offset().‌​top}, 500);
});

简化:DRY

function smoothScrollingTo(target){
  $('html,body').animate({scrollTop:$(target).offset().‌​top}, 500);
}
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    smoothScrollingTo(this.hash);
});
$(document).ready(function(){
  smoothScrollingTo(location.hash);
});

href*=\\#的解释:

  • *表示它与包含# char的内容匹配。因此只匹配锚点。有关此含义的更多信息,请参阅here
  • \\是因为#是css选择器中的特殊字符,所以我们必须将其转义。

答案 2 :(得分:28)

CSS3中的新热点。这比此页面上列出的每种方法都容易得多,并且不需要Javascript。只要在您的CSS中输入以下代码,所有指向您自己页面内部位置的链接就会突然出现滚动动画。

html{scroll-behavior:smooth}

之后,任何指向div的链接都将平滑地滑到那些部分。

<a href="#section">Section1</a>

顺便说一句,我花了数小时试图使它生效。在一些晦涩的注释部分找到了解决方案。这是越野车,无法在某些标签中使用。在体内没有作用。当我将其放在CSS文件的html {}中时,它终于可以工作了。

答案 3 :(得分:21)

$('a[href*=#]').click(function(event){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    event.preventDefault();
});

这对我来说很完美

答案 4 :(得分:14)

我很惊讶没有人发布了一个原生解决方案,它也负责更新浏览器位置哈希以匹配。这是:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

请参阅教程:http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml

答案 5 :(得分:11)

我建议你制作这个通用代码:

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

    $('html, body').animate({
        scrollTop:$(the_id).offset().top
    }, 'slow');

return false;});

你可以在这里看到一篇非常好的文章:jquery-effet-smooth-scroll-defilement-fluide

答案 6 :(得分:6)

$(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/

答案 7 :(得分:4)

原生支持哈希ID滚动的平滑滚动。

html {
  scroll-behavior: smooth;
}

您可以看一下:https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

答案 8 :(得分:4)

使用JQuery:

$('a[href*=#]').click(function(){
  $('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
  }, 500);
  return false;
});

答案 9 :(得分:3)

仅CSS

@Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mapFragment != null) {
            while (getFragmentManager() == null) {
                try {
                    Thread.sleep(500);
                }
                catch (InterruptedException e) {
                    //e.printStackTrace();
                }
            }
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.map, mapFragment).commitAllowingStateLoss();
            mapFragment.getMapAsync(this);
        }

        return view;
    }

您只需要添加此内容。现在,您的内部链接滚动行为将像流一样平滑。

要了解详细信息,请阅读此article

答案 10 :(得分:3)

这里已经有很多好的答案-但是它们都缺少必须删除空锚的事实。否则,一旦单击空锚,这些脚本就会生成JavaScript错误。

我认为正确的答案是这样的:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();

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

答案 11 :(得分:2)

此解决方案也适用于以下网址,而不会破坏指向不同网页的锚链接。

http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor

./index.html
./index.html#anchor

var $root = $('html, body');
$('a').on('click', function(event){
    var hash = this.hash;
    // Is the anchor on the same page?
    if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
        $root.animate({
            scrollTop: $(hash).offset().top
        }, 'normal', function() {
            location.hash = hash;
        });
        return false;
    }
});

我还没有在所有浏览器中对此进行测试。

答案 12 :(得分:2)

这样可以很容易地让jQuery识别你的目标哈希并知道何时何地停止。

$('a[href*="#"]').click(function(e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);

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

答案 13 :(得分:2)

使用滚动行为可以做到这一点。添加以下属性。

    scroll-behavior: smooth;

就是这样。不需要JS。

a {
  display: inline-block;
  width: 50px;
  text-decoration: none;
}
nav, scroll-container {
  display: block;
  margin: 0 auto;
  text-align: center;
}
nav {
  width: 339px;
  padding: 5px;
  border: 1px solid black;
}
scroll-container {
  display: block;
  width: 350px;
  height: 200px;
  overflow-y: scroll;
  scroll-behavior: smooth;
}
scroll-page {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 5em;
}
<nav>
  <a href="#page-1">1</a>
  <a href="#page-2">2</a>
  <a href="#page-3">3</a>
</nav>
<scroll-container>
  <scroll-page id="page-1">1</scroll-page>
  <scroll-page id="page-2">2</scroll-page>
  <scroll-page id="page-3">3</scroll-page>
</scroll-container>

PS:请检查浏览器的兼容性。

答案 14 :(得分:2)

添加:

function () {
    window.location.hash = href;
}

以某种方式使垂直偏移

无效
top - 72

在Firefox和IE中,不在Chrome中。基本上,页面会根据偏移量平滑地滚动到它应该停止的点,但然后跳转到页面没有偏移的位置。

它确实将哈希添加到网址的末尾,但是按回来不会将您带回到顶部,它只是从网址中删除哈希并将查看窗口留在它所在的位置。

以下是我正在使用的完整js:

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top - 120
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

答案 15 :(得分:2)

给出的答案有效但禁用外发链接。在一个带有额外奖励的版本下方(摆动)并尊重外向链接。

[[y,airports[x]] for x,y in enumerate(cities)]

答案 16 :(得分:2)

HTML

<a href="#target" class="smooth-scroll">
    Link
</a>
<div id="target"></div>

或使用绝对完整网址

<a href="https://somewebsite.com/#target" class="smooth-scroll">
    Link
</a>
<div id="target"></div>

的jQuery

$j(function() {
    $j('a.smooth-scroll').click(function() {
        if (
                window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
            &&  window.location.hostname == this.hostname
        ) {
            var target = $j(this.hash);
            target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $j('html,body').animate({
                    scrollTop: target.offset().top - 70
                }, 1000);
                return false;
            }
        }
    });
});

答案 17 :(得分:2)

如今,现代浏览器的速度要快一些。 setInterval可能有效。这个功能在Chrome和Firefox中运行良好。(在Safari中有点慢,没有使用IE浏览器)

function smoothScroll(event) {
    if (event.target.hash !== '') { //Check if tag is an anchor
        event.preventDefault()
        const hash = event.target.hash.replace("#", "")
        const link = document.getElementsByName(hash) 
        //Find the where you want to scroll
        const position = link[0].getBoundingClientRect().y 
        let top = 0

        let smooth = setInterval(() => {
            let leftover = position - top
            if (top === position) {
                clearInterval(smooth)
            }

            else if(position > top && leftover < 10) {
                top += leftover
                window.scrollTo(0, top)
            }

            else if(position > (top - 10)) {
                top += 10
                window.scrollTo(0, top)
            }

        }, 6)//6 milliseconds is the faster chrome runs setInterval
    }
}

答案 18 :(得分:1)

经过测试和验证的代码

<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {

// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
  // Prevent default anchor click behavior
  event.preventDefault();

  // Store hash
  var hash = this.hash;

  // Using jQuery's animate() method to add smooth page scroll
  // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
  jQuery('html, body').animate({
    scrollTop: jQuery(hash).offset().top
  }, 800, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
  });
} // End if
});
});
</script>

答案 19 :(得分:1)

<script>
  // This example requires the Places library. Include the libraries=places
  // parameter when you first load the API. For example:
  // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

  var map;
  var infowindow;

  function initMap() {
    var pyrmont = {lat: 38.06908229560463,  lng: 46.31730562744135};

    map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch({
      location: pyrmont,
      radius: 1000,
      types: ['bus_station','transit_station']

    }, callback);
  }

  function callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
    }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(place.name);
      infowindow.open(map, this);
    });
  }
</script>

答案 20 :(得分:1)

永远不要忘记offset()函数正在为元素提供文档位置。因此,当您需要相对于其父元素滚动元素时,您应该使用它;

    $('.a-parent-div').find('a').click(function(event){
        event.preventDefault();
        $('.scroll-div').animate({
     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       
  });

关键点是获取scroll-div的scrollTop并将其添加到scrollTop。如果你不想做那个position()函数总是给你不同的位置值。

答案 21 :(得分:1)

如果您在页面上有一个简单的按钮向下滚动到div并希望后退按钮通过跳转到顶部来工作,只需添加以下代码:

$(window).on('hashchange', function(event) {
    if (event.target.location.hash=="") {
        window.scrollTo(0,0);
    }
});

这可以扩展到跳转到不同的div,通过读取哈希值,并像Joseph Silbers回答一样滚动。

答案 22 :(得分:1)

这是我为多个链接和锚点实现的解决方案,用于平滑滚动:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/ 如果您在导航div中设置了导航链接并使用此结构声明:

<a href = "#destinationA">

和您对应的锚标记目的地如下:

<a id = "destinationA">

然后将其加载到文档的头部:

    <!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

<script type = "text/javascript">
 $(document).ready(function()
    {
        // Scroll the whole document
        $('#menuBox').localScroll({
           target:'#content'
        });
    });
</script>

感谢@Adriantomic

答案 23 :(得分:1)

我为“/ xxxxx#asdf”和“#asdf”href锚点做了这个

$("a[href*=#]").on('click', function(event){
    var href = $(this).attr("href");
    if ( /(#.*)/.test(href) ){
      var hash = href.match(/(#.*)/)[0];
      var path = href.match(/([^#]*)/)[0];

      if (window.location.pathname == path || path.length == 0){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
        window.location.hash = hash;
      }
    }
});

答案 24 :(得分:0)

感谢分享,约瑟夫·西尔伯(Joseph Silber)。这是您2018年的ES6解决方案,仅作了少许改动以保持标准行为(滚动到顶部):

document.querySelectorAll("a[href^=\"#\"]").forEach((anchor) => {
  anchor.addEventListener("click", function (ev) {
    ev.preventDefault();

    const targetElement = document.querySelector(this.getAttribute("href"));
    targetElement.scrollIntoView({
      block: "start",
      alignToTop: true,
      behavior: "smooth"
    });
  });
});

答案 25 :(得分:0)

您可以将np.matmul(a,b) (2, 1, 1) array([[[1]], [[6]]]) window.scroll()设置为锚标签的偏移顶部使用behavior: smooth,以确保锚标签位于视口的顶部。

top

演示:

document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', function (e) {
        e.preventDefault();
        var href = this.getAttribute("href");
        var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
        //gets Element with an id of the link's href 
        //or an anchor tag with a name attribute of the href of the link without the #
        window.scroll({
            top: elem.offsetTop, 
            left: 0, 
            behavior: 'smooth' 
        });
        //if you want to add the hash to window.location.hash
        //you will need to use setTimeout to prevent losing the smooth scrolling behavior
       //the following code will work for that purpose
       /*setTimeout(function(){
            window.location.hash = this.hash;
        }, 2000); */
    });
});
a, a:visited{
  color: blue;
}

section{
  margin: 500px 0px; 
  text-align: center;
}

您只需将CSS属性<a href="#section1">Section 1</a> <br/> <a href="#section2">Section 2</a> <br/> <a href="#section3">Section 3</a> <br/> <a href="#section4">Section 4</a> <section id="section1"> <b style="font-size: 2em;">Section 1</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/> <section> <section id="section2"> <b style="font-size: 2em;">Section 2</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <section id="section3"> <b style="font-size: 2em;">Section 3</b> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <a style="margin: 500px 0px; color: initial;" name="section4"> <b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b> </a> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <script> document.querySelectorAll('a[href^="#"]').forEach(a => { a.addEventListener('click', function (e) { e.preventDefault(); var href = this.getAttribute("href"); var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]"); window.scroll({ top: elem.offsetTop, left: 0, behavior: 'smooth' }); }); }); </script>设置为scroll-behavior(大多数现代浏览器都支持)即可,而无需使用Javascript。

smooth
html, body{
  scroll-behavior: smooth;
}
a, a:visited{
  color: blue;
}

section{
  margin: 500px 0px; 
  text-align: center;
}

答案 26 :(得分:0)

在将哈希添加到浏览器url时,需要jquery并进行动画处理以使用指定名称(而不是id)锚定标记。还可修复大多数使用jquery的答案中的错误,该错误中的#号没有以转义的反斜杠作为前缀。不幸的是,后退按钮无法正确导航回以前的哈希链接...

$('a[href*=\\#]').click(function (event)
{
    let hashValue = $(this).attr('href');
    let name = hashValue.substring(1);
    let target = $('[name="' + name + '"]');
    $('html, body').animate({ scrollTop: target.offset().top }, 500);
    event.preventDefault();
    history.pushState(null, null, hashValue);
});

答案 27 :(得分:0)

好吧,解决方案取决于问题的类型,我使用javascript animate方法来单击按钮。并且我使用了波纹管链接中的代码作为导航栏

https://css-tricks.com/snippets/jquery/smooth-scrolling/

$(document).ready(function () {
  $(".js--scroll-to-plans").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-plans").offset().top,
      },
      1000
    );
    return false;
  });

  $(".js--scroll-to-start").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-features").offset().top,
      },
      1000
    );
    return false;
  });

  $('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
});