本文介绍了锚链接到页面的某个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接到另一个页面的锚链接。当它被点击时,默认它会进入下一页的顶部。我想把它带到页面的某个位置。如何做到这一点(无论是与jQuery幻灯片效果或正常的HTML)?



例如,当.sample a被点击时,我希望它带给你一个确定链接页面的位置。

解决方案

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



原因其他解决方案都没有工作,因为当页面加载时,隐藏匹配锚点的 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> 元素中添加 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.

这篇关于锚链接到页面的某个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 15:45
查看更多