[英]Can I use an anchor in an href to scroll to a location with classname and no id?
i'm using Javascript and I need an anchor to a classname cause we don't have id near the location.我正在使用 Javascript 并且我需要一个类名的锚点,因为我们在该位置附近没有 id。 Can I use an anchor in an href tag to doing this?
我可以在 href 标签中使用锚点来执行此操作吗?
The example is of an anchor with id's use:该示例是使用 id 的锚点:
<div id='anchorID'>
<a href='mysite.com#anchorID>
But can I do this if I have only classname?但是,如果我只有类名,我可以这样做吗? With anchor, not scrollInToView or something else:
使用锚,而不是 scrollInToView 或其他东西:
<div class='myclass'>
Thank you!谢谢!
Is it necessary for the URL to display this anchor? URL有必要显示这个锚点吗? If not read about scrollIntoView .
如果没有阅读有关scrollIntoView的信息。
If you need the url alone to accomplish the navigation, then id
or name
attributes (on the element itself) are your only options.如果您只需要 url 来完成导航,那么
id
或name
属性(在元素本身上)是您唯一的选择。
BTW, a nice visual effect for smoothly scrolling to a functioning anchor can be accomplished with a CSS property called scroll-behavior :顺便说一句,可以使用名为scroll-behavior的 CSS 属性来实现平滑滚动到正常工作的锚点的良好视觉效果:
html
{
scroll-behavior: smooth;
}
This has nothing to do with your issue, but I thought you might like it.这与您的问题无关,但我认为您可能会喜欢它。
only Href does not work with class.只有 Href 不适用于 class。 you can do with javascript/jQuery
你可以用 javascript/jQuery 做
<a href='javascript:void(0)' data-target='.myClass'>Link</a>
jQuery jQuery
$("[data-target]").on('click', function(){
var target_ = $(this).attr("data-target");
var targetSelector = $(target_);
if(targetSelector.length){
$("html, body").animate({ scrollTop: targetSelector.offset().top }, 1000);
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.