【问题标题】:links scroll to a div (class) and just one scroll (animate) in a different direction链接滚动到一个 div(类),并且只有一个滚动(动画)在不同的方向
【发布时间】:2014-11-14 11:57:16
【问题描述】:

我试图让很多链接滚动到一个 div,而只有一个滚动(动画)在不同的方向。

我的 html 看起来像这样:

<div class="top"> content here </div>

<ul>
  <li><a href="link1" class="bottom">link2</li>
  <li><a href="link2" class="bottom">link3</li>
  <li><a href="link3" class="bottom">link4</li>
  <li><a href="link4" class="bottom">link5</li>
  <li><a href="link5" class="bottom">link6</li>
</ul>

<p> content here </p>
<p> content here </p>
<p> content here </p>
<p> etc... </p>

<ul>
  <li><a href="link6" class="top">link1</li>
</ul>

<p> content here </p>
<p> content here </p>
<p> content here </p>
<p> etc... </p>

<div class="top"> content here </div>

所以 links2、3、4、5 和 6 将滚动到 div class="bottom"。

Link6 将滚动到顶部 div class="top"。

我无法更改链接本身,所以它必须通过使用类名来工作:

class="底部"

class="顶部"

如何用 jQuery 实现?

另外...我不想在链接或 div 中使用 ID。

【问题讨论】:

    标签: jquery class scrollto


    【解决方案1】:

    使用 window.scrollby(nHorizo​​ntal, nVertical);在带有 setTimout() 的点击处理程序中。像这样:

    $(".bottom").click(function() 
    { 
        setTimeout(500. function() { window.scrollBy(nHorizontal, nVertial) }); 
    }).
    

    并将链接的 href 更改为 #divBottom 并将 id 放在 div 上。

    setTimeout 是给页面初始滚动的时间。

    另一种方法显示在css-tricks.com

    代码:

    $(function() 
    {
      $('a[href*=#]:not([href=#])').click(function() 
      {
        var nDistance = 0; // Set to whatever distance this needs to scroll.
    
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
        &&  location.hostname == this.hostname) 
        {
          var aAnchor = $(this)
          var target  = $(this.hash.replace("#", ".")); // get target by class name
    
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    
          if (target.length) 
          {
              $('body').animate(
              {
                 scrollTop: target.offset().top
              }, 
              1000,
              function()
              {
                 $("body").animate({ scrollTop: nDistance }, 500);                 
              });
            return false;
          }
        }
      });
    });
    

    如果您想真正发挥创造力,请在锚点上设置一个数据属性,告诉每个锚点滚动多远。

    html

    <a href="#divBottom" data-scrollDistance="350" > Text <a/>
    

    从点击处理程序访问的javascript

    $(this).data("scrollDistance");
    

    【讨论】:

    • 谢谢,但正如我所说,我不想使用 ID。另外,我无法更改链接 href。
    • 已更新解决方案以完全符合标准。最重要的信息适合标题,以便未来的访问者可以找到他们的答案。我对 myanswer 又做了一项调整,它将解决您的问题。 :)
    • 好了!很抱歉最初的答案被关闭了,我需要得到我希望在这里出现的问题的答案。但是下面的解决方案显示了您需要的答案。
    • 更正了选择器的双重调用问题。
    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 2013-08-14
    • 2012-06-15
    • 2012-02-12
    • 2019-11-02
    • 1970-01-01
    • 2023-03-04
    • 2015-11-01
    相关资源
    最近更新 更多