如何在单击某个链接时让用户弹出到页面上的特定位置

时间:2013-04-04 23:38:20

标签: jquery

嘿伙计们我想弄清楚如何拥有一个用户,重定向到另一个页面,并根据点击的链接;让它把它们放在包含信息的页面的那个位置。

我打算在JQuery中对此进行编码。请让我知道:))

谢谢你们,我希望你们周四有一个Tremdous !!!

编辑:

<div class="online_training">
     <div class="training_image">
       <a href="../services.php">...</a>
     </div><!-- .training_image -->
     <div class="top-textArea">
       <h2><a href="../services.php"></a>....</h2>
       <p>
                       .....
       </p>
     </div><!-- .top-textArea -->
</div><!-- .online_training -->



    I have mutiple of these and so the part to notice where I want to have 
it redirect to and go to that part of the page is the where the .training_image <a> is and the <h2> one is.

3 个答案:

答案 0 :(得分:4)

最简单的方法是使用锚标签。

在首页上:

<a href="/otherpage#spot1">Go to spot1</a>

在其他页面上:

<a href="#" name="spot1"></a>

当加载其他页面时,它将滚动到名为spot1的锚点。

答案 1 :(得分:1)

如果由于某种原因你无法使用原始链接href到达那里......,你可以使用window.location和命名锚点的组合。

$('a').click(function(evt){
  evt.preventDefault();

  switch ($(this).prop('data-destination')) {
    case 'api':
      window.location = 'other-page.html#api';
      break;
    case 'tutorial':
      window.location = 'other-page.html#tut';
      break;
    default:
      window.location = 'other-page.html#toc';
      break;
  }
});

在other-page.html上你有那些名为锚点的地方,例如:

<a name="toc"></a>
<a name="api"></a>
<a name="tut"></a>

理想的解决方案是以正确的方式构建链接,避免使用javascript / jQuery。

答案 2 :(得分:1)

假设您在页面的顶部或某处有div这样的内容:

<div name="top-div">
    <a href="javascript:void(0)" id="clickMe">Click to Scroll</a>
</div>

然后在页面的下方,您可以在另一个div中找到目标:

<div id="scrollHere" name="scrollHere">
    Hi
</div>

使用类似下面的jQuery来获得花哨的滚动效果:

$("#clickMe").click(function(event) {
    event.preventDefault();
    var scrollTo = $("#scrollHere").css("top");
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, scrollTo);
});

jsFiddle

$("#clickMe").click(function(event) {
    event.preventDefault();
    $.fn.scrollToPos("#scrollHere");
});

$.fn.scrollToPos = function(position) {
    var scrollTo = $(position).css("top");
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, scrollTo);
    return this;
};

jsFiddle 2