且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

锚链接到页面的某个位置

更新时间:2023-12-02 23:44:34

好的,所以这个答案是非常具体的问题。



原因其他解决方案都没有工作,因为当页面加载时,隐藏匹配锚点的 div 元素将被隐藏。



为证明这一点,请点击主页上的链接,然后查看 not 工作。然后将哈希从 #whatever 更改为 #bgaboutbody ,您将看到它正常工作。

所以,使用这样的东西会使它适合你。基本上,如果有散列,它会动画到正确的位置。将它放在页面最底部的脚本块中(位于< / body> 标记的正上方)

  window.setTimeout(function(){
if(window.location.hash){
var $ target = $(window.location.hash).closest (#bgaboutbody);
if($ target.length)
('html,body')。animate({scrollTop:$ target.offset()。top},1000);
}
},100);

了解如何使用回退:



确保您的内容在没有JavaScript的情况下在像这样的销售网站上加载会更好。 (在网络应用程序中,我认为这是一个不同的讨论)。我会建议使用我给你的解决方案来这个问题< head> $ c>元素中添加 js 类到 html code>页面。然后将你的CSS范围如下所示:

  .js #contact,.js #about等等{display:none} 

所以只有JS存在才会隐藏。此外,由于这个解决方案也使用JavaScript,所以它的重要性在JS被禁用时仍然可见,因此它仍然可用。


I have an anchor link which links to another page. When it is clicked, by default it goes to the top of the next page. I want it brought to a certain position of the page. How do I do this (either with a jQuery slide effect or normal html)?

For instance, when .sample a is clicked I want it to bring you to a certain position of the linking page.

OK, so this answer is very specific to your problem.

The reason none of the other solutions worked is that your div elements that would match the anchor are hidden when the page loads.

To prove this out, click on of your links on the home page, and see it not work. Then change the hash from #whatever to #bgaboutbody and you will see it work properly.

So, using something like this will make it work for you. Basically, if there is a hash, it will animate down to the correct spot. Put this in a script block at the very bottom of your page (right above the </body> tag)

window.setTimeout(function(){
    if(window.location.hash){
        var $target  = $(window.location.hash).closest("#bgaboutbody");
        if($target.length)
            $('html, body').animate({scrollTop: $target.offset().top}, 1000);
    }
}, 100);

Learn to use fallbacks:

It is always better to make sure your content will load without JavaScript on a sales site like this. (In a web app I feel that is a different discussion). I would recommend using the solution I gave you to this question where you add a js class to the html element in the <head> of the page. Then scope your CSS like this:

.js #contact, .js #about, etc { display:none }

So it will only be hidden if JS is present. Additionally, since this solution is also using JavaScript its important they are visible if JS is disabled so it still works.