[英]Scrolling with the mouse scroll to the height of the blocks
当滚动页面滚动恰好发生在其中的块的高度(内部代码)时怎么办?
我不想使用该库,因为,当在块的高度滚动(预定数量的像素)时,可能需要添加2-5行代码来解决滚动页面的问题。
第二个问题是如何使这个平滑滚动,这不是刚刚从一个单元切换到另一个单元的感觉。
function slide() { h = document.documentElement.clientHeight $(".one, .two, .three").css('height', h); }; $(window).resize(slide); $(document).ready(slide);
.one, .two, .two { display: block; position: relative; width: 100%; } .one { background: #CD5; } .two { background: aquamarine; } .three { background: #2196F3; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="one"></div> <div class="two"></div> <div class="three"></div>
将滚动处理程序绑定到mousewheel和DOMMouseScroll事件,并使用(event.originalEvent.wheelDelta> 0 || event.originalEvent.detail <0)来确定滚动的方向。 然后使用$()。offset()。top来查找要滚动的div的顶部和$ .animate()来进行滚动。
function slide() { h = document.documentElement.clientHeight $(".one, .two, .three").css('height', h); }; $(window).resize(slide); $(document).ready(slide); $(document).bind('mousewheel DOMMouseScroll', function(event) { scroll(event); }); var num = 1; var scrolling = false; function scroll(event) { event.preventDefault(); if (!scrolling) { scrolling = true; if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) { num--; num = num < 1 ? 1 : num; } else { num++; num = num > 3 ? 3 : num; } $('html, body').animate({ scrollTop: $(".num" + num).offset().top }, 500, "linear", function() { scrolling = false; }); } }
.one, .two, .two { display: block; position: relative; width: 100%; } .one { background: #CD5; } .two { background: aquamarine; } .three { background: #2196F3; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="one num1"></div> <div class="two num2"></div> <div class="three num3"></div>
根据我的理解,我已经在jsfiddle上创建了一个解决方案,请查看https://jsfiddle.net/v7ok83oa/
我正在使用mousewheel事件。
HTML
<div class="one">
<h1>ONE</h1></div>
<div class="two">
<h1>Two</h1></div>
<div class="three">
<h1>Three</h1></div>
CSS
* {
margin: 0;
padding: 0
}
.one,
.two,
.three {
display: block;
position: relative;
width: 100%;
overflow: auto;
}
.one {
background: #CD5;
}
.two {
background: aquamarine;
}
.three {
background: #2196F3;
}
h1 {
color: white;
text-align: center;
}
jQuery的
$(document).ready(function() {
var h = $(document).height();
var body = $("body");
$(".one, .two, .three").css('height', h);
$(document).on('mousewheel', function(e) {
if (e.originalEvent.wheelDelta / 120 < 0) { // if Mouse wheel up
var st = $(document).scrollTop();
body.animate({
scrollTop: st + h
}, '500');
} else if (e.originalEvent.wheelDelta / 120 > 0) { // if Mouse wheel down
var st = $(document).scrollTop();
body.animate({
scrollTop: st - h
}, '500');
}
console.log($('.one').height());
});
});
更新检查此https://jsfiddle.net/v7ok83oa/3/
如果您在动画结束之前非常快速地滚动事件触发器,我已修复它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.