简体   繁体   English

是否可以按类而不是 id 跳转到 HTML 元素?

[英]Is it possible to jump to HTML element by class instead of id?

I know that you can jump to elements by id but is it possible to jump to elements by class?我知道您可以通过 id 跳转到元素,但是否可以通过类跳转到元素?

Am I going to have to use javascript to add an id to the element with that class name?我是否必须使用 javascript 向具有该类名的元素添加 id?

It would be a pain to add ids manually every time, the class names will already be there.每次手动添加 id 会很痛苦,类名已经存在了。

*I could have worded my question a bit better. *我可以更好地表达我的问题。 I meant to use class names that are already there as anchor tags to jump to.我的意思是使用已经存在的类名作为要跳转到的锚标签。 The html I'm working with has class names for a LOT of individual elements and no ids.我正在使用的 html 有很多单个元素的类名,没有 id。 I'm wanting to jump to those elements without having to add an id to each and every one.我想跳转到这些元素,而不必为每个元素添加 id。

window.scrollTo(0, document.querySelector(".className").offsetTop);

http://jsfiddle.net/DerekL/kEFp7/

Even though i wouldn't recommend to use a class to jump to an element...即使我不建议使用类跳转到元素...

You can use this a couple of different jQuery such as ScrollTo or ScrollTop您可以使用这几个不同的 jQuery,例如ScrollToScrollTop

FYI: On chrome you can create an anchor to a text , which will take you to that section and also highlight the text.仅供参考:在 chrome 上,您可以为文本创建一个锚点,这将带您到该部分并突出显示文本。

The most common syntax is: #:~:text=Some text最常见的语法是: #:~:text=Some text

And all possible usages are: #:~:text=[prefix-,]textStart[,textEnd][,-suffix] which would allow you to select text from , to , inclusive / exclusive所有可能的用法是: #:~:text=[prefix-,]textStart[,textEnd][,-suffix]这将允许您选择文本from , to , inclusive / exclusive

Consider the following example links:考虑以下示例链接:

Specs: W3C community draft report规格: W3C 社区草案报告

document.getElementsByClassName('className')

或者,使用 jQuery

$('.className')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM