6

在我的主页底部,我包含了一个联系表格,并将此部分的锚指定为 div id="contact"。

在任何页面上单击联系按钮时,它应该导航到主页并在页面加载时自动滚动到联系表格。

在查看了我在此处找到的类似问题后,我一直未能成功地使其工作:jQuery scroll to ID from different page 当我尝试时,它只是跳转到表单。我希望它平滑滚动。

<li><span>Get in touch</span><a href="index.html#contact">Contact</a></li>

问题 jquery 函数从其他页面滚动到主页上的联系人锚点:

(function($){
    var jump=function(e) {
        if (e) {
            e.preventDefault();
            var target = $(this).attr("href");
        } else {
            var target = location.hash;
        }

        $('html,body').animate({
            scrollTop: $(target).offset().top
        },1000,function() {
            location.hash = target;
        });
    }

    $('html, body').hide()

    $(document).ready(function() {
        $('a[href^=#]').bind("click", jump);

    if (location.hash) {
        setTimeout(function(){
            $('html, body').scrollTop(0).show()
            jump()
        }, 0);
    } else {
      $('html, body').show()
    }
});

我正在尝试实现与此示例类似的内容:http: //vostrel.cz/so/9652944/page.html 不同之处在于,在这种情况下,锚点 ID(联系)对我来说只出现在一页(主页)上。

4

3 回答 3

1

试试这个,你的脚本没问题,只是缺少最后一行

 (function ($) {

     var jump = function (e) {
         if (e) {

             e.preventDefault();
             var target = $(this).attr("href");

         } else {

             var target = location.hash;

         }
         $('html,body').animate({

             scrollTop: $(target).offset().top

         }, 1000, function () {

             location.hash = target;

         });
     }

     $('html, body').hide();

     $(document).ready(function () {
         $('a[href^=#]').bind("click", jump);

         if (location.hash) {
             setTimeout(function () {

                 $('html, body').scrollTop(0).show()
                 jump();

             }, 0);
         } else {

             $('html, body').show();

         }
     });
 })(jQuery)
于 2015-02-11T21:29:46.523 回答
0

我在测试您的代码时遇到的小提示:

因为您使用的是锚标记的 href 属性,所以它以#contact 的形式出现,jQuery 将其解释为 ID。

无论它位于哪个页面,您都需要向锚点添加一个 id="contact" 以使其正常工作。

于 2012-12-11T09:16:20.767 回答
0

我不确定你的代码是什么,但我已经能够让它工作。一件事是,您发布的代码})(jQuery)最后缺少 a 。不管怎样,看看我在这里做了什么,我想这就是你要找的。我不确定您网站的 HTML 是什么样的,但我认为您可以调整它。您需要做的就是将联系人按钮的 href 属性设置为index.html#contact. 在 index.html 上,你可以使用#contact它,它会做同样的事情。

在 index.html 中,标题:

<div id="header">
    <a href="index.html">Homepage</a>
    <a href="otherpage.html">Other page</a>
    <a href="otherpage2.html">Another Page</a>
    <a href="#contact">Contact</a>
</div>

但在任何其他页面:

<div id="header">
    <a href="index.html">Homepage</a>
    <a href="otherpage.html">Other page</a>
    <a href="otherpage2.html">Another Page</a>
    <a href="index.html#contact">Contact</a>
</div>

在 index.html 的标题中删除index.html可防止页面被加载两次,因此 jQuery 只需向下滚动页面。

于 2012-08-05T21:42:35.663 回答