2012-08-05 77 views
6

在我的主页底部,我已经包含了一个联系表单,并为本节指定了div id =“contact”。链接到不同的页面 - > jquery滚动到特定的锚点

当任何页面上的联系人按钮被点击时,它应该导航到主页和页面加载,自动滚动到联系表格。

我在检查了一个类似的问题之后,在找到这里之后,我一直没有成功: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”,锚点ID(联系人)对我来说只出现在一页(家庭)上。

回答

0

我不确定你的代码是什么,但我已经能够得到它的工作。有一件事是,你发布的代码,最后缺少})(jQuery)。无论如何,看看我做了什么here,我想这就是你要找的。我不确定你的网站的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只是向下滚动页面。

0

小技巧中,我遇到了同时检测出你的代码:

因为你使用的锚标记的href属性,它过来的#contact,其中jQuery的解释为一个ID。

无论页面处于何种状态,您都需要向锚点添加一个id =“contact”以使其工作。

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)