将 HTML 页面滚动到响应式页面中给定锚点的最佳方法

Sam*_*des 0 html css

我已经基于此响应式模板创建了一个页面

https://html5up.net/uploads/demos/phantom/
Run Code Online (Sandbox Code Playgroud)

我希望这些块在同一页面上有一个锚点:当您单击它时,它会向您显示内容(不会重定向到不同的页面)

实现这一目标的最佳“现代”方法是什么?普通锚链接/jquery/css 其他?

你能给我举个例子吗?

谢谢

Nik*_*ppa 5

根据我的说法,最好的方法是将目标内容放在带有 ID(显然是唯一的)的同一页面上<div id="generic"> ..content.. </div>,并在<a>标签的上href,使用带有 的 ID 来定位所需的 div href="#generic"。像这样

<a href="#generic">
  <h2>Magna</h2>
  <div class="content">
     <p>Sed nisl arcu euismod sit ame.</p>
  </div>
</a>
.....
.....
.....
<div id="generic">..</div>
Run Code Online (Sandbox Code Playgroud)

除此之外,添加平滑滚动,使其看起来像是向上/向下滑动到目标内容。

如果不添加#generic到您的网址,请尝试在上述代码之外使用超级简单的 JQuery 修复:

$("article a").click(function(e){
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
    }, 1500);
    e.preventDefault(); //this is the important line.
});
Run Code Online (Sandbox Code Playgroud)

我已经在你的网站上测试过了,它的效果就像一个魅力!如果有任何问题请告诉我。