Javascript:如何增强鼠标滚动到目标区域
我有个问题,请帮忙Javascript:如何增强鼠标滚动到目标区域,javascript,scroll,action,Javascript,Scroll,Action,我有个问题,请帮忙 如何使用Javascript读取滚动事件(鼠标滚动到顶部或底部) 以及如何在读到鼠标滚动后触发一些事件 结构将是这样的 <div id="listofstuff"> <div class="anitem"> <span class="itemname">Item1</span> <span class="itemdescruption">AboutItem1</span> </div
- 如何使用Javascript读取滚动事件(鼠标滚动到顶部或底部)
- 以及如何在读到鼠标滚动后触发一些事件
<div id="listofstuff">
<div class="anitem">
<span class="itemname">Item1</span>
<span class="itemdescruption">AboutItem1</span>
</div>
<div class="anitem">
<span class="itemname">Item2</span>
<span class="itemdescruption">AboutItem2</span>
</div>
<div class="anitem">
<span class="itemname">Item3</span>
<span class="itemdescruption">AboutItem3</span>
</div>
<div class="anitem">
<span class="itemname">Item4</span>
<span class="itemdescruption">AboutItem5</span>
</div>
<div class="anitem">
<span class="itemname">Item5</span>
<span class="itemdescruption">AboutItem5</span>
</div>
项目1
大约1
项目2
大约平方米
项目3
大约m3
项目4
大约5
项目5
大约5
比方说,用户第一次访问我的网站时,他们将看到项目1
向下滚动后,页面将自动平滑滚动至项目2
现在,当它们在项目2中时
- 如果向下滚动,则转到项目3
- 如果向上滚动,则返回到项目1
+1最佳答案:)我建议您使用这个漂亮的jquery插件,以避免在所有浏览器中都与本机鼠标事件发生过多冲突。。。 然后,您可以滚动到鼠标事件的正确位置: $(函数(){
从窃取您需要使用JavaScript来监听“鼠标滚轮”事件 然后使用事件e.wheelDelta来计算用户滚动的方向 我必须使用以防止事件被多次触发,从而导致幻灯片滚动到底部
var amountOfSlides = 4;
var counter = 1; //at slide
var main = document.getElementById('main');
var currentPos = 0;
//The scroll event fires way to many times so we need to use
//debounce to only get the event once per scroll;
window.addEventListener('mousewheel', debounce(function(e) {
//Check to see if the scroll is going up or down.
if(e.wheelDelta >= 0) {
//going up so make sure that the user isn't already at the top
if(counter <= 1) return;
currentPos = currentPos + window.innerHeight;
counter--;
} else {
//going down. make sure the user is not at the bottom.
if(counter >= amountOfSlides) return;
currentPos = currentPos - window.innerHeight;
counter++;
}
//change the position of the margin so that the slides move.
document.getElementById('main').style.marginTop = currentPos + "px";
}, 250));
// http://remysharp.com/2010/07/21/throttling-function-calls/
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
为了简单起见,我没有使用您的HTML,但是您可以自己轻松地更改它
<section id="main">
<article></article>
<article></article>
<article></article>
<article></article>
</section>
html, body, #main{
height:100%;
margin:0;
}
body {
overflow:hidden;
}
#main {
transition:1s;
}
article {
height:100%;
}
<section id="main">
<article></article>
<article></article>
<article></article>
<article></article>
</section>