所以我尝试使用JavaScript on scroll
来调用函数。但我想知道我是否可以在不使用jQuery的情况下检测滚动的方向。如果没有,那么有没有解决方法?
我当时正想着把一个'放到顶部'按钮,但如果可以,我想避免使用。
我现在只是尝试使用此代码,但它没有工作:
if document.body.scrollTop <= 0 {
alert ("scrolling down")
} else {
alert ("scrolling up")
}
答案 0 :(得分:106)
可以通过存储前一个scrollTop值并将当前的scrollTop值与它进行比较来检测它。
JS:
var lastScrollTop = 0;
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
element.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);
答案 1 :(得分:35)
捕捉所有滚动事件(触摸和滚轮)的简单方法
window.onscroll = function(e) {
// print "false" if direction is down and "true" if up
console.log(this.oldScroll > this.scrollY);
this.oldScroll = this.scrollY;
}
答案 2 :(得分:18)
使用此选项查找滚动方向。这只是为了找到垂直滚动的方向。支持所有跨浏览器。
var scrollableElement = document.getElementById('scrollableElement');
scrollableElement.addEventListener('wheel', findScrollDirectionOtherBrowsers);
function findScrollDirectionOtherBrowsers(event){
var delta;
if (event.wheelDelta){
delta = event.wheelDelta;
}else{
delta = -1 * event.deltaY;
}
if (delta < 0){
console.log("DOWN");
}else if (delta > 0){
console.log("UP");
}
}
答案 3 :(得分:6)
这是对prateek所回答的补充。在IE中的代码中似乎有一个小故障所以我决定修改它有点没什么特别的(只是另一个条件)
$('document').ready(function() {
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
console.log("down")
}
else if(st == lastScrollTop)
{
//do nothing
//In IE this is an important condition because there seems to be some instances where the last scrollTop is equal to the new one
}
else {
console.log("up")
}
lastScrollTop = st;
});});
答案 4 :(得分:5)
您可以尝试这样做。
import {Component, ViewChild, OnInit, ElementRef, Renderer2} from '@angular/core';
import {
NgbDatepicker,
NgbInputDatepicker,
NgbDateStruct,
NgbCalendar,
NgbDateAdapter,
NgbDateParserFormatter} from '@ng-bootstrap/ng-bootstrap';
...
export class NgbdDatepickerPopup implements OnInit{
...
@ViewChild('myRangeInput') myRangeInput: ElementRef;
constructor(element: ElementRef, private renderer: Renderer2, private _parserFormatter: NgbDateParserFormatter) { }
onDateSelection(date: NgbDateStruct) {
let parsed = ''; // initializing with empty string
if (!this.fromDate && !this.toDate) {
this.fromDate = date;
} else if (this.fromDate && !this.toDate && after(date, this.fromDate)) {
this.toDate = date;
this.input.close();
} else {
this.toDate = null;
this.fromDate = date;
}
if(this.fromDate) {
// if fromDate is set: add the first date
parsed += this._parserFormatter.format(this.fromDate);
}
if(this.toDate) {
// if toDate is set: add the second date with separator
parsed += ' - ' + this._parserFormatter.format(this.toDate);
}
// here we update the input value with the new parsed value
this.renderer.setProperty(this.myRangeInput.nativeElement, 'value', parsed);
}
function scrollDetect(){
var lastScroll = 0;
window.onscroll = function() {
let currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value
if (currentScroll > 0 && lastScroll <= currentScroll){
lastScroll = currentScroll;
document.getElementById("scrollLoc").innerHTML = "Scrolling DOWN";
}else{
lastScroll = currentScroll;
document.getElementById("scrollLoc").innerHTML = "Scrolling UP";
}
};
}
scrollDetect();
html,body{
height:100%;
width:100%;
margin:0;
padding:0;
}
.cont{
height:100%;
width:100%;
}
.item{
margin:0;
padding:0;
height:100%;
width:100%;
background: #ffad33;
}
.red{
background: red;
}
p{
position:fixed;
font-size:25px;
top:5%;
left:5%;
}
答案 5 :(得分:2)
您可以使用document.documentElement.scrollTop
获取滚动条位置。然后,只需将其与之前的位置进行比较即可。
答案 6 :(得分:2)
此简单的代码将起作用:检查控制台的结果。
let scroll_position = 0;
let scroll_direction;
window.addEventListener('scroll', function(e){
scroll_direction = (document.body.getBoundingClientRect()).top > scroll_position ? 'up' : 'down';
scroll_position = (document.body.getBoundingClientRect()).top;
console.log(scroll_direction);
});
答案 7 :(得分:1)
//初始化
let oldValue = 0;
//收听事件
window.addEventListener('scroll', function(e){
// Get the new Value
newValue = window.pageYOffset;
//Subtract the two and conclude
if(oldValue - newValue < 0){
console.log("Up");
} else if(oldValue - newValue > 0){
console.log("Down");
}
// Update the old value
oldValue = newValue;
});
答案 8 :(得分:0)
我个人使用此代码来检测javascript中的滚动方向... 只需定义一个变量来存储lastscrollvalue,然后使用if&else
let lastscrollvalue;
function headeronscroll() {
// document on which scroll event will occur
var a = document.querySelector('.refcontainer');
if (lastscrollvalue == undefined) {
lastscrollvalue = a.scrollTop;
// sets lastscrollvalue
} else if (a.scrollTop > lastscrollvalue) {
// downscroll rules will be here
lastscrollvalue = a.scrollTop;
} else if (a.scrollTop < lastscrollvalue) {
// upscroll rules will be here
lastscrollvalue = a.scrollTop;
}
}
答案 9 :(得分:0)
虽然接受的答案有效,但值得注意的是,它将以很高的速度触发。这可能会导致计算量大的操作出现性能问题。
MDN的建议是限制事件。下面是他们的示例的修改,增强后可以检测滚动方向。
修改自:https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event
// ## function declaration
function scrollEventThrottle(fn) {
let last_known_scroll_position = 0;
let ticking = false;
window.addEventListener("scroll", function () {
let previous_known_scroll_position = last_known_scroll_position;
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function () {
fn(last_known_scroll_position, previous_known_scroll_position);
ticking = false;
});
ticking = true;
}
});
}
// ## function instantiation
scrollEventThrottle((scrollPos, previousScrollPos) => {
if (previousScrollPos > scrollPos) {
console.log("going up");
} else {
console.log("going down");
}
});
答案 10 :(得分:-1)
简单代码
// Events
$(document).on('mousewheel DOMMouseScroll', "element", function(e) {
let delta = e.originalEvent.wheelDelta;
if (delta > 0 || e.originalEvent.detail < 0) upScrollFunction();
if (delta < 0 || e.originalEvent.detail > 0) donwScrollFunction();
}