스크롤 방향을 감지하는 방법
누군가 요소에서 아래로 스크롤 할 때 함수를 실행하고 싶습니다. 이 같은:
$('div').scrollDown(function(){ alert('down') });
$('div').scrollUp(function(){ alert('up') });
그러나 그러한 기능은 존재하지 않습니다. 이 문제에 대한 해결책이 있습니까? 그들은 그것을 할 수있는 것 같습니다. 불행히도 소스 코드는 압축되어 있으므로 운이 없습니다 ...
감사합니다 !!
나는 결국 그것을 알아낼 수 있었으므로 누군가가 답을 찾고 있다면 :
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
다음 예제는 터치 나 트랙 패드 스크롤없이 마우스 스크롤 만 듣습니다.
jQuery.on ()을 사용 합니다 ( jQuery 1.7부터 .on () 메서드는 이벤트 핸들러를 문서에 첨부하는 데 선호되는 메서드입니다).
$('#elem').on( 'DOMMouseScroll mousewheel', function ( event ) {
if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
//scroll down
console.log('Down');
} else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
모든 브라우저에서 작동합니다.
바이올린 : http://jsfiddle.net/honk1/gWnNv/7/
이것은 업데이트가 필요합니다-요즘 우리는 wheel
이벤트가 있습니다 :
$(function() {
$(window).on('wheel', function(e) {
var delta = e.originalEvent.deltaY;
if (delta > 0) $('body').text('down');
else $('body').text('up');
return false; // this line is only added so the whole page won't scroll in the demo
});
});
body {
font-size: 22px;
text-align: center;
color: white;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
이미 꽤 오랫동안 최신 브라우저에서 지원이 꽤 좋았습니다.
- Chrome 31 이상
- Firefox 17 이상
- IE9 +
- 오페라 18+
- Safari 7 이상
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
더 깊은 브라우저 지원이 필요한 경우 다음을 망쳐 놓는 대신 mousewheel.js를 사용하는 것이 가장 좋습니다.
https://plugins.jquery.com/mousewheel/
$(function() {
$(window).mousewheel(function(turn, delta) {
if (delta > 0) $('body').text('up');
else $('body').text('down');
return false; // this line is only added so the whole page won't scroll in the demo
});
});
body {
font-size: 22px;
text-align: center;
color: white;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
기존 솔루션
이 게시물과 다른 stackoverflow 기사 에서 3 가지 해결책 이있을 수 있습니다 .
해결책 1
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('up 1');
}
else {
console.log('down 1');
}
lastScrollTop = st;
});
해결 방법 2
$('body').on('DOMMouseScroll', function(e){
if(e.originalEvent.detail < 0) {
console.log('up 2');
}
else {
console.log('down 2');
}
});
해결책 3
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('up 3');
}
else {
console.log('down 3');
}
});
다중 브라우저 테스트
Safari에서 테스트 할 수 없습니다.
크롬 42 (Win 7)
- 해결책 1
- Up : 스크롤 1 개당 이벤트 1 개
- Down : 스크롤 1 개당 이벤트 1 개
- 해결책 2
- Up : 작동하지 않음
- 다운 : 작동하지 않음
- 해결책 3
- Up : 스크롤 1 개당 이벤트 1 개
- Down : 스크롤 1 개당 이벤트 1 개
Firefox 37 (Win 7)
- 해결책 1
- Up : 스크롤 1 개당 20 개 이벤트
- Down : 스크롤 1 개당 20 개 이벤트
- 해결책 2
- Up : 작동하지 않음
- Down : 스크롤 1 개당 이벤트 1 개
- 해결책 3
- Up : 작동하지 않음
- 다운 : 작동하지 않음
IE 11 (Win 8)
- 해결책 1
- Up : 1 스크롤 당 10 개 이벤트 (부작용 : 드디어 다운 스크롤 발생)
- Down : 스크롤 1 개당 10 개 이벤트
- 해결책 2
- Up : 작동하지 않음
- 다운 : 작동하지 않음
- 해결책 3
- Up : 작동하지 않음
- Down : 스크롤 1 개당 이벤트 1 개
IE 10 (Win 7)
- 해결책 1
- Up : 스크롤 1 개당 이벤트 1 개
- Down : 스크롤 1 개당 이벤트 1 개
- 해결책 2
- Up : 작동하지 않음
- 다운 : 작동하지 않음
- 해결책 3
- Up : 스크롤 1 개당 이벤트 1 개
- Down : 스크롤 1 개당 이벤트 1 개
IE 9 (Win 7)
- 해결책 1
- Up : 스크롤 1 개당 이벤트 1 개
- Down : 스크롤 1 개당 이벤트 1 개
- 해결책 2
- Up : 작동하지 않음
- 다운 : 작동하지 않음
- 해결책 3
- Up : 스크롤 1 개당 이벤트 1 개
- Down : 스크롤 1 개당 이벤트 1 개
IE 8 (Win 7)
- 해결책 1
- Up : 1 스크롤 당 2 건 (부작용 : 드디어 다운 스크롤 발생)
- Down : 스크롤 1 개당 2 ~ 4 개 이벤트
- 해결책 2
- Up : 작동하지 않음
- 다운 : 작동하지 않음
- 해결책 3
- Up : 스크롤 1 개당 이벤트 1 개
- Down : 스크롤 1 개당 이벤트 1 개
결합 된 솔루션
IE 11과 IE 8의 부작용이
if else
성명서 에서 오는지 확인했습니다 . 그래서if else if
다음과 같은 진술로 대체했습니다 .
멀티 브라우저 테스트에서 일반적인 브라우저 에는 솔루션 3 을 사용 하고 파이어 폭스 및 IE 11에는 솔루션 1 을 사용하기로 결정했습니다 .
IE 11을 감지하기 위해이 답변 을 참조 했습니다 .
// Detect IE version
var iev=0;
var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var rv=navigator.userAgent.indexOf("rv:11.0");
if (ieold) iev=new Number(RegExp.$1);
if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
if (trident&&rv!=-1) iev=11;
// Firefox or IE 11
if(typeof InstallTrigger !== 'undefined' || iev == 11) {
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('Up');
}
else if(st > lastScrollTop) {
console.log('Down');
}
lastScrollTop = st;
});
}
// Other browsers
else {
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('Up');
}
else if(e.originalEvent.wheelDelta < 0) {
console.log('Down');
}
});
}
$(function(){
var _top = $(window).scrollTop();
var _direction;
$(window).scroll(function(){
var _cur_top = $(window).scrollTop();
if(_top < _cur_top)
{
_direction = 'down';
}
else
{
_direction = 'up';
}
_top = _cur_top;
console.log(_direction);
});
});
데모 : http://jsfiddle.net/AlienWebguy/Bka6F/
다음은 쉬운 방법을 보여주는 샘플 입니다. 스크립트는 다음과 같습니다.
$(function() {
var _t = $("#container").scrollTop();
$("#container").scroll(function() {
var _n = $("#container").scrollTop();
if (_n > _t) {
$("#target").text("Down");
} else {
$("#target").text("Up");
}
_t = _n;
});
});
The #container
is your div id
. The #target
is just to see it working. Change to what you want when up or when down.
EDIT
The OP didn't say before, but since he's using a div with overflow: hidden
, scrolling doesn't occur, then the script to detect the scroll is the least of it. Well, how to detect something that does not happen?!
So, the OP himself posted the link with what he wants, so why not use that library? http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js.
The call is just:
$(function() {
$(".scrollable").scrollable({ vertical: true, mousewheel: true });
});
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$(document).bind(mousewheelevt,
function(e)
{
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0)
{
scrollup();
}
else
{
scrolldown();
}
}
);
You can use this simple plugin to add scrollUp
and scrollDown
to your jQuery
https://github.com/phpust/JQueryScrollDetector
var lastScrollTop = 0;
var action = "stopped";
var timeout = 100;
// Scroll end detector:
$.fn.scrollEnd = function(callback, timeout) {
$(this).scroll(function(){
// get current scroll top
var st = $(this).scrollTop();
var $this = $(this);
// fix for page loads
if (lastScrollTop !=0 )
{
// if it's scroll up
if (st < lastScrollTop){
action = "scrollUp";
}
// else if it's scroll down
else if (st > lastScrollTop){
action = "scrollDown";
}
}
// set the current scroll as last scroll top
lastScrollTop = st;
// check if scrollTimeout is set then clear it
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
// wait until timeout done to overwrite scrolls output
$this.data('scrollTimeout', setTimeout(callback,timeout));
});
};
$(window).scrollEnd(function(){
if(action!="stopped"){
//call the event listener attached to obj.
$(document).trigger(action);
}
}, timeout);
참고URL : https://stackoverflow.com/questions/7154967/how-to-detect-scroll-direction
'Program Tip' 카테고리의 다른 글
UIImage의 둥근 모서리 (0) | 2020.12.09 |
---|---|
ORM 및 Embedded SQL없이 Java 웹 애플리케이션을 디자인하려면 어떻게해야합니까? (0) | 2020.12.09 |
아직없는 경우 배열에 추가 (0) | 2020.12.09 |
5 분마다 URL 주소를 실행하는 CRON 명령 (0) | 2020.12.09 |
C ++ 14에 도입 된 어떤 변경으로 인해 C ++ 11로 작성된 프로그램이 잠재적으로 중단 될 수 있습니까? (0) | 2020.12.09 |