锚标记,使用 jQuery 转到 div 类的开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1567836/
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-26 11:44:51  来源:igfitidea点击:

Anchor tag, to go to the beginning of a div class w/ USING jQuery

jqueryhtml

提问by Brad

I want to implement a global anchor type of functionality.

我想实现一个全局锚类型的功能。

I want to include a link to the main part of the web page, globally by inputting into my header.inc file.

我想通过输入到我的 header.inc 文件中,在全局范围内包含一个指向网页主要部分的链接。

When you select the link, it will scroll to the main part of the page, which is within the div class content-body

当您选择链接时,它将滚动到页面的主要部分,该部分位于 div 类 content-body 中

<div class="content-body">
  main content
</div>

So it will scroll down to where the div begins.

所以它会向下滚动到 div 开始的地方。

I want to achieve the anchor tag functionality, but it goes to a div class, not id.

我想实现锚标记功能,但它转到一个 div 类,而不是 id。

I want to know if there is a way to do this with jQuery. Why I want to do this, is because I can globally implement this throughout the entire existing website.

我想知道是否有办法用 jQuery 做到这一点。我之所以要这样做,是因为我可以在整个现有网站中全局实现这一点。

回答by Pjl

This may help you.

这可能对你有帮助。

You can create a small function to make this behavior. Is realy usefull. You cant totally avoid open windows or modals, and things like that.

您可以创建一个小函数来实现此行为。是真的有用。你不能完全避免打开窗口或模式,以及类似的事情。

 function to_position(divid){
     $('html, body').animate({scrollTop:$(divid).position().top - 50 }, 'slow');
 }

So. you use the function like this.

所以。你像这样使用这个功能。

 to_position('#my_id')
 //or class, or whatever jquery selector
 to_position('.my_class')
 //
 to_position('input[name="lorenzolamas"]')

回答by slant

Well, traditionally this is done by using an id attribute on an element and making the anchor point to that id.

嗯,传统上这是通过在元素上使用 id 属性并使锚点指向该 id 来完成的。

<a href="#main">Go to Main Element</a>

<div id="main"></div>

The hash tag is the key as that indicates that you're wanting to direct the user to somewhere within the same document.

散列标签是关键,因为它表明您希望将用户定向到同一文档中的某个位置。

This is, of course, assuming that you are not saying that the class attached to the 'main' element in question is your only option.

当然,这是假设您不是说附加到所讨论的“主要”元素的类是您唯一的选择。

回答by Buggabill

You could use scrollTopin jQuery. Here is a pagethat shows this.

您可以在 jQuery 中使用scrollTop。这是一个显示这一点的页面