用JS创建一个很好的滚动/滑动效果 [英] Create a nice scrolling/sliding effect with JS
问题描述
我想创建一个从一个元素向下滑动的平滑滚动动画。我不想使用Jquery或任何库,只是javascript和HTML。我试过:
I would like to create a "smooth" scroll animation that slides down from one element to the next. I do not want to use Jquery or any libraries, just javascript and HTML. I have tried:
element.scrollIntoView();
这导致滚动,但不能平滑的动画。我已经看了一些其他平滑滚动的技术,但他们使用Jquery。我还要补充说,滚动应该是从页面上的ELEMENT到页面上的另一个ELEMENT。仅向下滚动。另外只有JavaScript函数像函数scrollFromHere(from,to)
。
This causes scrolling, but not a smooth animation. I have already looked at some other smooth-scrolling techniques, but they use Jquery. I would also like to add that the scrolling should be from ELEMENT on a page to another ELEMENT on the page. Scroll down only. Also only javascript function like function scrollFromHere(from, to)
.
推荐答案
Never mind, I think I found an answer to my question. It took lots of searching, but here it is:
<div id="elem1"><button onclick="scrollToward('elem2', 'elem1');">Scroll Down</button></div>
<div id="elem2"></div>
<script>
//Here is my script:
function animate(elem,style,unit,from,to,time,prop) {
if( !elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1,(new Date().getTime()-start)/time);
if (prop) {
elem[style] = (from+step*(to-from))+unit;
} else {
elem.style[style] = (from+step*(to-from))+unit;
}
if( step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
function scrollToward(ele, from) {
var target = document.getElementById(ele);
from = document.getElementById(from).offsetTop;
animate(document.body, "scrollTop", "", from, target.offsetTop, 1500, true);
}
</script>
以创建滚动条的方式对div进行样式测试和工作。找到答案此处。
Tested and works when you style the divs in a way that creates a scrollbar. Found the answer here.
这篇关于用JS创建一个很好的滚动/滑动效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!