使用jquery平滑滚动到另一个页面上的ID Div



我有一个页面"link.html",它有一个指向index.html页面<a href = "index.html?#myInnerLink"的锚点

我想平滑滚动到另一个页面(index.html(上的div,该页面在jquery中的Id为"myInnerLink"。。它运行良好,但问题是它从下到上滚动,而不是从上到下滚动到特定的div

"myInnerLink"div在"myDiv"div中是内部的…谢谢

link.html

<a id="mylink" href="index.html?#myInnerLink">Go To MY InnerLink</a>

index.html

<div id="myDiv" class="mydiv">
SomeText here...
<div id="myInnerLink">
ScrollTo This Div...
</div>
</div>

jquery

$(document).ready(function() {
if (window.location.hash) {
var hash = window.location.hash;
$('#myDiv').animate({
scrollTop :  $(hash).offset().top
}, 500);
};
});

我目前正在使用下面的脚本,该脚本经过修改,最初来自https://jsfiddle.net/s61x7c4e/

function doScrolling(element, duration) {
let bodyRect = document.body.getBoundingClientRect(),
elementRect = element.getBoundingClientRect(),
offset = ((elementRect.top - bodyRect.top) - 40);
let startingY = window.pageYOffset,
elementY = offset,
targetY,
diff,
easeInOutCubic,
start;
duration = duration || 500;
// if element is close to page's bottom then window will scroll only to some position above the element...
targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY;
diff = targetY - startingY;
easeInOutCubic = function (t) {
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
};
if (!diff) return;
// bootstrap our animation,
//  it will get called right before next frame shall be rendered...
window.requestAnimationFrame(function step(timestamp) {
if (!start) start = timestamp;
let time = timestamp - start, // elapsed milliseconds since start of scrolling...
percent = Math.min(time / duration, 1); // get percent of completion in range [0, 1]
// apply the easing, it can cause bad-looking
//  slow frames in browser performance tool, so be careful...
percent = easeInOutCubic(percent);
window.scrollTo(0, startingY + diff * percent);
// proceed with animation as long as we wanted it to.
if (time < duration) {
window.requestAnimationFrame(step)
}
})
}
document.getElementById('scrollMid').addEventListener('click', function(){
	var element = document.getElementById('middle');
	doScrolling(element, 1000);
});

最新更新