Haphazard滚动双击jquery

时间:2018-03-02 09:53:05

标签: javascript jquery html css

我试图通过使用jquery点击锚标签列表来直接在div标签上滚动。

enter code here
        function scrollThere(targetElement, speed) {
       // initiate an animation to a certain page element:
      $('html, body , #side').stop().animate(
      { scrollTop: targetElement.offset().top }, // move window so target 
      element is at top of window
      speed, // speed in milliseconds
     'swing' // easing
      ); // end animate
    } // end scrollThere function definition


     //--- START NAV-ITEM CLICK EVENTS ---//
    // when the user clicks a nav item:
    $("#leftSidebar ul li a").click(function (e) {

    e.preventDefault(); // don't jump like a typical html anchor

    // find the index of the "#" character in the href string...
    var startOfName = $(this).attr('href').indexOf("#"),
    // ...then use it as the argument in the slice() method (add 1 so you 
    don't include the # character).
    clickRef = $(this).attr('href').slice(startOfName + 1),
     targetEl = $('a[name=' + clickRef + ']'); // select the element this 
     link is pointing to

    // scroll there smoothly:
    scrollThere(targetEl, 400);

    });

问题在于,当我点击链接两次时,它会将我带到页面顶部,滚动也会混乱。由于某些原因,滚动因为div标签的大小增加而正常工作。这是一个显示问题的小提琴https://jsfiddle.net/60tp46y3/18/。通常点击左侧的相应链接,右侧部分应滚动到相应的ID。

1 个答案:

答案 0 :(得分:0)

刚刚修改了你的代码。它现在正在工作。

https://jsfiddle.net/t0of2kzp/

错误是,您没有检查容器的当前滚动位置,其中包含所有其他元素。

// targetElement is the div surrounding the target a tag.
var postionOfTargetElement = targetElement.offset().top;
// That's the main container
var scrollPosition = targetElement.parent().scrollTop();
// Here we calculate the real top position with respecting the main containers scroll position.
var topTarget = postionOfTargetElement + scrollPosition;