Html 使用 URL 中没有 # 的锚点滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15223006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:09:12  来源:igfitidea点击:

Scroll with anchor without # in URL

javascripthtmlhash

提问by mayank

I need to scroll through a page using anchor tag.

我需要使用anchor tag.

Right now I'm doing:

现在我正在做:

<a href="#div1">Link1</a>

<div id='div1'>link1 points me!!</div>

This works fine when I clicked on Link1, the page scrolls to the div with id "div1".
The point is, I do not want to change my URL which takes #divas suffix once I clicked on Link1.

当我单击 Link1 时,这工作正常,页面滚动到 ID 为“div1”的 div。
关键是,我不想更改我#div点击后作为后缀的URL Link1

I tried with anchor href as

我尝试使用锚href作为

void(0);

and

location.hash='#div1';
return false;

e.preventdefault;

How to avoid changing the URL?

如何避免更改URL?

回答by henser

Take this answer from Jeff Hines using jQuery's animate:

使用 jQuery 的 animate 从 Jeff Hines 那里得到这个答案:

function goToByScroll(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

If you're using jQuery don't forget to add the library to your project.

如果您使用 jQuery,请不要忘记将库添加到您的项目中。

Edit: Also, make sure that you still "return false;" in the click handler for the link, otherwise it'll still add the "#div1" to your URL (thanks @niaccurshi)

编辑:另外,确保你仍然“返回假;” 在链接的点击处理程序中,否则它仍会将“#div1”添加到您的 URL(感谢 @niaccurshi)

回答by stallingOne

scrollIntoViewdid the best job when all other methods failed!

scrollIntoView当所有其他方法都失败时,做得最好!

document.getElementById('top').scrollIntoView(true);

Where 'top'is the id of the html tag you want to go.

哪里'top'是你想去的HTML标签的ID。

回答by mknayab

Make your life easier, try the following and let me know if there is anything else ;-)

让您的生活更轻松,请尝试以下操作,如果还有其他问题,请告诉我 ;-)

<div>top</div>
<div style="height: 800px;">&nbsp;</div>
<div><a href="javascript:void(0);" onclick="window.scroll(0,1);">click here</a></div>

FYI:You only need to play around with one/single line href="javascript:void(0);" onclick="window.scroll(0,1);"and it works for you.

仅供参考:你只需要玩一条/单条线href="javascript:void(0);" onclick="window.scroll(0,1);",它对你有用。

Have a good day!

祝你有美好的一天!

回答by Sayg?n Karahan

Only Add this code into jquery on document ready

仅在文档准备好时将此代码添加到 jquery 中

Ref : http://css-tricks.com/snippets/jquery/smooth-scrolling/

参考:http: //css-tricks.com/snippets/jquery/smooth-scrolling/

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

回答by dhc

Riffing off Henser's answer, I have a case where the window.location.hashis already set, and the user then scrolls back to the top of the page (where the hash link is).

根据 Henser的回答,我有一个window.location.hash已经设置的情况,然后用户滚动回页面顶部(哈希链接所在的位置)。

Since the hash is already set, you can re-locate on clicking that link by:

由于已经设置了哈希,您可以通过以下方式在单击该链接时重新定位:

$(window).scrollTop($('a[name='+id+']').offset().top);

回答by edsonski

I'm know I'm 4 years late, but you guys can try this.

我知道我迟到了 4 年,但你们可以试试这个。

HTML:

HTML:

<a href="#div1">Link1</a>
<!-- you can put <br />'s here to see effect -->
<div id='div1'>link1 points me!!</div>
<!-- <br />'s here, too, to see effect -->

JavaScript/jQuery

JavaScript/jQuery

$(document).ready(function(){
    $('a').on('click', function(event) {
        event.preventDefault();
        var hash = this.hash;
        $('html, body').animate({scrollTop: $(hash).offset().top}, 900);
    });
})

回答by Manoj Selvin

Add smooth scroll to any item click including anchor, button etc without adding div id to URL :)

将平滑滚动添加到任何项目点击,包括锚点、按钮等,而无需向 URL 添加 div id :)

Info:scrollIntoViewOptions(Optional){ behavior: "auto" | "instant" | "smooth", block: "start" | "end", }

信息:scrollIntoViewOptions(可选){行为:“自动”| “即时” | "顺利", 块: "开始" | “结尾”, }

function scrollSmoothTo(elementId) {
  var element = document.getElementById(elementId);
  element.scrollIntoView({
    block: 'start',
    behavior: 'smooth'
  });
}
#userdiv {
  margin-top: 200px;
  width: 200px;
  height: 400px;
  border: 1px solid red;
}
<button onclick="scrollSmoothTo('userdiv')">
  Scroll to userdiv
</button>

<div id="userdiv">
  Lorem ipsum this is a random text
</div>

DEMO

演示

Reference: https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

参考:https: //developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView