将按钮链接到另一个页面的一部分

link a button to a part of another page

本文关键字:一部分 另一个 按钮 链接      更新时间:2023-09-26

我有一个指向另一个页面的链接按钮,它可以工作,但我希望链接指向该页面的特定部分。我知道我应该使用jquery,出于某种原因,它没有跳到我想跳到的部分。

我的按钮链接:

 <div class="btn_holder top-slide"><a 
  href="http://testurl.com/media#isabelo"><p class="leeu_button">READ
  MORE</p></a>
 </div>

我目前拥有的内容会滚动到页面底部,而不是id="isabello"的部分。所以这个jquery有效,但不是我想要的。希望你能理解。

$(document).ready(function(){ 
//check if hash tag exists in the URL
if(window.location.hash) {          
    $("html, body").animate({ scrollTop: $(document).height() }, 1000);
    1000);      
}     });

我也已经尝试过这个(根本不起作用):

$(document).ready(function(){ 
//check if hash tag exists in the URL
if(window.location.hash) {          
     $('html, body').animate({ scrollTop: $("#isabelo").offset().top }, 1000);      
}
     });

我试图链接到的页面有一个id="isabelo"的div

<div class="content_holder terms_row" id="isabelo">
<a href="http://www.example.com/some-page-or-other.html#exactline">Click here</a>

要跳转到的位置应该具有name="exactline"属性

您不应该为此使用jquery。您应该能够使用直接的html链接到"media/pagename.html#isabelo"。但是您缺少页面名称。这一点,你需要在上面有一个NAME标签和ID。

我在同一页中尝试过,结果成功了。我不是jquery的专家,但如果:

 $("html, body").animate({ scrollTop: $(document).height() }, 1000);

工作,但与isabello不工作,可能是因为浏览器还没有加载isabello所在的html。试着调试一下,看看你是否在这一点上有Isabello元素,或者它还没有加载。

我发现的另一件不同的事情是,在第一个例子中,你把"1000"放了两倍

$("html,body").animate({scrollTop:$(document).height()},1000)1000)

在第二个不是

$('html,body').animate({scrollTop:$("#isabello").offset().top},1000)

但我怀疑这是一个复制/粘贴的错误,因为在第一个例子中,我找不到它的意义,但它正如你所说的那样有效。

我的解决方案:

$(document).ready(function(){    
//check if hash tag exists in the URL
if(window.location.hash) {   
setTimeout(function(){
     $('html, body').animate({ scrollTop: $("#isabelo").offset().top },
 1000); 
 },1000);       
  }      
}); 

使用超时函数稍后加载。已解决:)


setInterval将是比setTimeout更好的方法。如果您的页面没有在1秒内加载,那么setTimeout中的代码将无法按预期工作。但是,如果您每秒钟都有一个间隔,并在获得该元素后清除该间隔,那么这将始终有效。

$(document).ready(function(){    
//check if hash tag exists in the URL
if(window.location.hash) {   
a = setInterval(function(){
     if($("#isabelo").length) {
       $('html, body').animate({ scrollTop: $("#isabelo").offset().top },
       1000);
       clearInterval(a);
     } 
 },1000);       
  }      
});