Haphazard双击jquery滚动

问题描述 投票:1回答:1

我试图通过使用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);

    });

问题是,当我点击一个链接两次,它带我到页面的顶部和滚动混乱。滚动由于某种原因dosent正常工作随着div标签的大小增加。这是一个小提琴https://jsfiddle.net/60tp46y3/18/显示问题。理想的是,点击左边的相应链接,右侧部分应滚动到相应的ID。

javascript jquery html css
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.