如何跳转到每个 JavaScript 特定页面的 h2 的 hrefs?

How to jump to hrefs of h2 for specific pages per JavaScript?

这是有效的(示例是 h2 标签的 ID。):

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 54;
    $('a[href^=#]').on('click', function(e){
        var href = $(this).attr('href');
        $('html, body').animate({
            scrollTop:$(href).offset().top -menubarHeight }, 1);
    });
});

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 154;
    $('a[href^=#idofh2]').on('click', function(e){
        var href = $(this).attr('href');
        $('html, body').animate({
            scrollTop:$(href).offset().top -menubarHeight }, 1);
    });
});

这不起作用(我希望此功能仅适用于此页面的 h2 的所有 hrefs -> https://example.com/, https://example.com/2):

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 154;
    $('a[href^=#]').on('click', function(e){
        // Here you can see, that there is h2. I don't know where to place it.
        var href = $(this).attr('h2');
        $('html, body').animate({
            scrollTop:$(href).offset().top -menubarHeight }, 1);
    });
});

我用的是1,因为我想跳转,没有流畅的滚动。我可以用什么代替 .animate?

如果我使用这个:

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 54;
    $('a[href^=#]').on('click', function(e){
        var href = $(this).attr('href');
        $('html, body').css("scrollTop", $(href).offset().top -menubarHeight);
    });
});

那么 54 行不通了。

这个:

$('a[href^=#]')

一般为54.

还有这个:

$('a[href^=#idofh2]')

是一个页面的一个h2标签的id。这样可行。但是我怎样才能将它用于所有 h2 标签并且只用于页面 https://example.com/, https://example.com/2?如果我跳转到 h2 标签,它必须是 154 (menubarHeight) 否则 54.

首先,如果你只需要改变 scrollTop 你可以使用 "css" 方法而不是动画:

.css({
        scrollTop:$(href).offset().top -menubarHeight
});

.css("scrollTop", $(href).offset().top -menubarHeight);

我不太明白你的问题!您要按 link 滚动标题(h2 标签)吗?

如果你只想跳转到一个有 id 的 dom,你可以将它称为 link

<a href="#idOfTheDom">Jump</a>

这不会导致侧面重新加载。

如果我理解错误,请提供更多信息。

<a href="#1">Jump</a>
<div style="height:500px"></div>
<h2 id="1">This is the H2</h2>
<div style="height:500px"></div>

根据你的问题,我猜你想做的是将 menuHeight 设置为 154 或 54,具体取决于 href 的目标是否指向 <h2> 元素与否。这时候jQuery的.is()方法就派上用场了。

因此,您可以简单地使用 .is('h2') 方法来检查所选节点的标记名是否匹配 h2:

jQuery(document).ready(function($){
    $('a[href^=#]').on('click', function(e){
        var href = $(this).attr('href');

        // Store the target element reference
        var $target = $(href);

        // Check if target element is a <h2> element
        var isTargetH2 = $target.is('h2');

        // Use ternary operators to set menuHeight
        // - If target element is <h2>, use 154
        // - Otherwise, use 54
        var menubarHeight = isTargetH2 ? 154 : 54;

        $('html, body').css("scrollTop", $target.offset().top - menubarHeight);
    });
});