使用香草JavaScript平滑地滚动到元素
我在使用vanilla JavaScript平滑滚动到元素时遇到了一些问题 我有一个有3个链接的单页网站。当我单击其中一个链接时,我希望平滑地滚动到它所代表的部分。我有一个jQuery版本,它工作得很好,但我想学习如何使用vanilla JavaScript实现相同的结果 这个问题以前提过,但答案有点复杂。我相信应该有一个更干净更简单的答案 谢谢 jQuery代码:使用香草JavaScript平滑地滚动到元素,javascript,Javascript,我在使用vanilla JavaScript平滑滚动到元素时遇到了一些问题 我有一个有3个链接的单页网站。当我单击其中一个链接时,我希望平滑地滚动到它所代表的部分。我有一个jQuery版本,它工作得很好,但我想学习如何使用vanilla JavaScript实现相同的结果 这个问题以前提过,但答案有点复杂。我相信应该有一个更干净更简单的答案 谢谢 jQuery代码: $('a').click(function(){ $('html, body').animate({ sc
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 1000);
return false;
});
您将需要一些平滑滚动的缓和功能 他是个放松的人 我有一个关于HTML5的课程。你可能对资料来源感兴趣 上述示例中使用的滚动演示功能:
function scrollToItemId(containerId, srollToId) {
var scrollContainer = document.getElementById(containerId);
var item = document.getElementById(scrollToId);
//with animation
var from = scrollContainer.scrollTop;
var by = item.offsetTop - scrollContainer.scrollTop;
if (from < item.offsetTop) {
if (item.offsetTop > scrollContainer.scrollHeight - scrollContainer.clientHeight) {
by = (scrollContainer.scrollHeight - scrollContainer.clientHeight) - scrollContainer.scrollTop;
}
}
var currentIteration = 0;
/**
* get total iterations
* 60 -> requestAnimationFrame 60/second
* second parameter -> time in seconds for the animation
**/
var animIterations = Math.round(60 * 0.5);
(function scroll() {
var value = easeOutCubic(currentIteration, from, by, animIterations);
scrollContainer.scrollTop = value;
currentIteration++;
if (currentIteration < animIterations) {
requestAnimationFrame(scroll);
}
})();
//without animation
//scrollContainer.scrollTop = item.offsetTop;
}
//example easing functions
function linearEase(currentIteration, startValue, changeInValue, totalIterations) {
return changeInValue * currentIteration / totalIterations + startValue;
}
function easeOutCubic(currentIteration, startValue, changeInValue, totalIterations) {
return changeInValue * (Math.pow(currentIteration / totalIterations - 1, 3) + 1) + startValue;
}
函数scrollToItemId(containerId、srollToId){
var scrollContainer=document.getElementById(containerId);
var item=document.getElementById(scrollToId);
//充满活力
var from=scrollContainer.scrollTop;
var by=item.offsetTop-scrollContainer.scrollTop;
如果(从scrollContainer.scrollHeight-scrollContainer.clientHeight){
by=(scrollContainer.scrollHeight-scrollContainer.clientHeight)-scrollContainer.scrollTop;
}
}
var currentIteration=0;
/**
*获取总迭代次数
*60->requestAnimationFrame 60/秒
*第二个参数->动画的时间(秒)
**/
var=数学四舍五入(60*0.5);
(功能滚动条(){
var值=easeOutCubic(当前迭代、起始迭代、结束迭代);
scrollContainer.scrollTop=值;
当前迭代++;
if(currentIteration
到底出了什么问题?请提供一个例子。我希望获得与jQuery代码相同的结果,但使用普通Javascript。我想不出如何实现它。如果有熟悉Javascript的人能够编写代码,我将不胜感激。谢谢你的回答。有没有更简单的方法呢?