I was searching for a way to prevent being taken to the top of a page after clicking a link with #
inside the href
attribute:
<a href="#" onclick="foobar()">click me</a>
and then I came across this simple solution, switching #
for #!
:
<a href="#!" onclick="foobar()">click me</a>
There were various other solutions available online using jQuery for instance:
$('.service').click(function(e) {
e.preventDefault();
});
I ended up liking #!
the most for being so clean BUT I COULDN'T find any documentation anywhere online as to what was actually happening when inserting the !
in the line of code.
QUESTION:
What is #!
actually causing the html code to do? Is this a good way to prevent the default action of taking the user to the top of the page, or is this method bad for other reasons? What I'm afraid of is that it might be a hacky method that isn't compatible with some browsers.
答案 0 :(得分:10)
实际导致html代码的
#!
是什么?
它告诉浏览器,当点击该链接时,它应该将页面滚动到锚点!
。由于页面上没有此类锚点,因此页面不会移动。 (从技术上讲,你可能在页面上有一个名为!
的锚[!
是一个完全有效的HTML id
值。。它只是...你可能没有。)
您可以通过为元素分配id
值(或使用过时的<a name="...">...</a>
构造)在页面上创建锚点; href
带有片段标识符(#
后面的位)告诉浏览器加载资源(在您的示例中,它是当前页面,已加载)然后向下滚动到该锚点。例如,如果您在页面上有<div id="foo">...</div>
,导航到该页面上的#foo
,浏览器将向下滚动以显示该div。当您提供不存在的锚点时,不会进行滚动。