gpt4 book ai didi

javascript - 如何根据 JavaScript 跳转到特定页面的 h2 的 hrefs?

转载 作者:行者123 更新时间:2023-11-30 20:05:05 26 4
gpt4 key购买 nike

这是可行的(示例是 h2-Tag 的 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。

最佳答案

如果你只想跳转到一个有id的dom,你可以调用它作为一个链接

<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>

关于javascript - 如何根据 JavaScript 跳转到特定页面的 h2 的 hrefs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com