admin管理员组文章数量:1310325
I'm trying to make a horizontal scroll website, but I don't know how to smoothly scroll from one element to the other. I tried the following code:
$("a[href='#top']").click(function() {
$("body").animate({ scrollTop: 0 }, "slow");
return false;
});
But it only scrolls to the top, I also tried the jQuery-plugin ScrollTo, but I just can't get it to work, I also tried the jQuery plugin:
$('.click').click(function(){
$.scrollTo( '.last', 800, {easing:'elasout'});
});
But also without succes.
Does anyone know a good, easy to understand, sample I can use? Thanks in advance!
I'm trying to make a horizontal scroll website, but I don't know how to smoothly scroll from one element to the other. I tried the following code:
$("a[href='#top']").click(function() {
$("body").animate({ scrollTop: 0 }, "slow");
return false;
});
But it only scrolls to the top, I also tried the jQuery-plugin ScrollTo, but I just can't get it to work, I also tried the jQuery plugin:
$('.click').click(function(){
$.scrollTo( '.last', 800, {easing:'elasout'});
});
But also without succes.
Does anyone know a good, easy to understand, sample I can use? Thanks in advance!
Share Improve this question edited Apr 24, 2016 at 17:42 MattAllegro 7,4055 gold badges49 silver badges57 bronze badges asked Feb 23, 2011 at 11:02 Jay WitJay Wit 3,0577 gold badges34 silver badges34 bronze badges 1- You need to tell us what isn't "working". You got error messages? What debugging did you try? – Lightness Races in Orbit Commented Feb 23, 2011 at 11:14
2 Answers
Reset to default 4untested
$('.click').click(function(){
$.scrollTo( $('.last'), 800);
});
In case you have to / need to avoid using jQuery here is vanilla JS solution which worked for us nicely:
function scrollToElement(myElement, scrollDuration = 500) {
const elementExists = document.querySelector(myElement);
if (elementExists && elementExists.getBoundingClientRect) {
const rect = elementExists.getBoundingClientRect();
const elementTop = rect.top + window.scrollY - 200; // a bit of space from top
var cosParameter = (window.scrollY - elementTop) / 2,
scrollCount = 0,
oldTimestamp = performance.now();
function step(newTimestamp) {
console.log(scrollCount);
scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
if (scrollCount >= Math.PI) {
window.scrollTo(0, elementTop);
return;
}
window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)) + elementTop);
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
}
scrollToElement("#yourElement");
I hope it helps :)
本文标签: Smooth JavaScriptjQuery scroll to elementStack Overflow
版权声明:本文标题:Smooth JavaScriptjQuery scroll to element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741818149a2399199.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论