假设您有一个隐藏了溢出的元素,是否可以在不滚动的情况下捕获该元素上的鼠标滚动?
我问这个的原因是;我有一个单页设计的网站,我编写了一个脚本,当您向下或向上滚动时,该脚本会自动滚动到下一个位置。但有一些我不想要的东西。当他们尝试滚动时,页面实际上是在真正意义上滚动,然后函数触发滚动以滚动到下一个位置。我计划将 body
的 overflow
设为 hidden
,这样他们将看不到滚动,只能看到自动滚动。
例如:
HTML
<body>
<div id="blue" class="clicked">
</div>
<div id="red" class="clicked">
</div>
<div id="green" class="clicked">
</div>
</body>
CSS
body{
overflow:hidden;
margin:0;
}
#blue{
background-color:blue;
width:100vw;
height:100vh;
}
#red{
background-color:red;
width:100vw;
height:100vh;
}
#green{
background-color:green;
width:100vw;
height:100vh;
}
JS
$(document).ready(function(){
$(document).scroll(function(){
$('body').animate({'scrollTop':'1000'},3000);
});
});
<强> DEMO
最佳答案
这是一个包含元素 overflow:hidden
并在位置之间滚动的示例:
var scroll_blocked = false;
$('.scrollable').on('mousewheel DOMMouseScroll', function (e) {
if (!scroll_blocked){
var delta = (e.originalEvent.wheelDelta || -e.originalEvent.detail);
if (delta < 0){
var new_pos = $('.scrollable').scrollTop() + $('.scrollable').height();
if (new_pos > ($('.scrollable_inner').height() - $('.scrollable').height())) return false;
} else if (delta > 0){
var new_pos = $('.scrollable').scrollTop() - $('.scrollable').height();
if (new_pos < 0) return false;
}
// scroll to new position
$('.scrollable').animate({'scrollTop': new_pos}, 500);
scroll_blocked = true;
setTimeout(function(){
scroll_blocked = false;
}, 500);
}
// disable all other scroll
return false;
});
.scrollable {
height: 200px;
width: 200px;
overflow: hidden;
}
.scrollable_inner {
}
.box {
height: 200px;
width: 100%;
}
.box_green {
background-color: green;
}
.box_blue {
background-color: blue;
}
.box_red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollable">
<div class="scrollable_inner">
<div class="box box_green">First slide - hover and scroll down</div>
<div class="box box_blue">Middle slide</div>
<div class="box box_red">Last slide -scroll up</div>
</div>
</div>
对于整个页面,将事件监听器附加到:
// mouse
$('html').on('mousewheel DOMMouseScroll', function (e) { ...
// touch
$('body').on('touchmove', function(e) { ...
滚动整个页面
$('html,body').animate({'scrollTop': ...
关于javascript - 捕获溢出时的滚动 :Hidden elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48478298/