firefox+jQuery mousewheel прокрутка события ошибка
обновление рабочее исправление, предложенное Дэвидом (см. ниже):
ОРИГИНАЛЬНЫЙ ПОСТ
Firefox 16.0.2 (последний) показывает проблему при привязке события» mousewheel / DOMMouseScroll». Прокрутка с помощью колесика мыши, когда указатель мыши находится поверх моего целевого div, также вызывает прокрутку окна, хотя я, очевидно, этого не хочу.
Я пробовал добавлять несколько методов для того чтобы остановить распространение etc. но ничего не получается.
чтобы увидеть его в действии, перейдите по ссылке jsFiddle ниже. На странице примера просто поместите указатель мыши внутри div с красными полями и используйте колесо прокрутки мыши. Firefox прокручивает родительское окно в первый раз (неожиданно), в то время как другие браузеры этого не делают.
странно, что Firefox не повторяет поведение после запуска события на связанном элементе, что означает, что он перестает прокручивать страницу. Однако он повторяет это поведение после прокрутки страницы вручную и повторите попытку.
Я также протестировал это в IE9 и Chrome, но не смог обнаружить эту проблему в этих браузерах (что означает, что они не прокручивают окно неожиданно), поэтому я предполагаю, что это специфично для Firefox (также отключен каждый плагин в firefox и т. д.)
это действительно ошибка в firefox (и если да, то есть кросс-браузерный хак, который может сделать трюк)? Или, если вы знаете о любом другом решении для достижения того же эффекта ловли события mousewheel без прокрутки окна страницы, Пожалуйста, не стесняйтесь отвечать!
4 ответов
Я не могу воспроизвести эту ошибку в моем FF 16.01 OSX с помощью сенсорной панели (Скрипка работает нормально), но я знаю, что есть еще одно событие mozilla, называемое MozMousePixelScroll. Возможно, вы захотите попробовать вовлечь и это.
в качестве sidenote я думаю, что остановка действия по умолчанию с помощью e.preventDefault() должны достаточно, нет необходимости останавливать распространение, а также (если нет других IE конкретных ошибок).
чтение https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference/DOMMouseScroll кажется, Mozmousepixelsscroll DOMMouseScroll был для firefox 16 или ранее. Для firefox >17 используйте wheel событие.
этот ответ на этот вопрос имеет наиболее совместимое с браузерами решение, которое я нашел:
этот ответ является решением crossbrowsing на Chrome, Firefox и iexplorer определяет
Источник
Get mouse wheel events in jQuery?
Is there a way to get the mouse wheel events (not talking about scroll events) in jQuery?
15 Answers 15
Binding to both mousewheel and DOMMouseScroll ended up working really well for me:
This method is working in IE9+, Chrome 33, and Firefox 27.
Edit — Mar 2016
I decided to revisit this issue since it’s been a while. The MDN page for the scroll event has a great way of retrieving the scroll position that makes use of requestAnimationFrame , which is highly preferable to my previous detection method. I modified their code to provide better compatibility in addition to scroll direction and position:
This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+
As of now in 2017, you can just write
Works with current Firefox 51, Chrome 56, IE9+
There’s a plugin that detects up/down mouse wheel and velocity over a region.
Answers talking about «mousewheel» event are refering to a deprecated event. The standard event is simply «wheel». See https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel
This worked for me:)
Here is a vanilla solution. Can be used in jQuery if the event passed to the function is event.originalEvent which jQuery makes available as property of the jQuery event. Or if inside the callback function under we add before first line: event = event.originalEvent; .
This code normalizes the wheel speed/amount and is positive for what would be a forward scroll in a typical mouse, and negative in a backward mouse wheel movement.
Demo: http://jsfiddle.net/BXhzD/
There is also a plugin for jQuery, which is more verbose in the code and some extra sugar: https://github.com/brandonaaron/jquery-mousewheel
This is working in each IE, Firefox and Chrome’s latest versions.
I was stuck in this issue today and found this code is working fine for me
The plugin that @DarinDimitrov posted, jquery-mousewheel , is broken with jQuery 3+. It would be more advisable to use jquery-wheel which works with jQuery 3+.
If you don’t want to go the jQuery route, MDN highly cautions using the mousewheel event as it’s nonstandard and unsupported in many places. It instead says that you should use the wheel event as you get much more specificity over exactly what the values you’re getting mean. It’s supported by most major browsers.
my combination looks like this. it fades out and fades in on each scroll down/up. otherwise you have to scroll up to the header, for fading the header in.
the above one is not optimized for touch/mobile, I think this one does it better for all mobile:
If using mentioned jquery mousewheel plugin, then what about to use the 2nd argument of event handler function — delta :
I think many key things are a bit all over the place and I needed to read all the answers to make my code work as I wanted, so I will post my findings in just one place:
- You should use «wheel» event over the other deprecated or browser specific events.
- Many people here is getting something wrong: the opposite of x>0 is x and the opposite of x is x>=0 , many of the answers in here will trigger scrolling down or up incorrectly when x=0 (horizontal scrolling).
- Someone was asking how to put sensitivity on it, for this you can use setTimeout() with like 50 ms of delay that changes some helper flag isWaiting=false and you protect yourself with if(isWaiting) then don’t do anything. When it fires you manually change isWaiting=true and just below this line you start the setTimeout again who will later change isWaiting=false after 50 ms.
I got same problem recently where $(window).mousewheel was returning undefined
What I did was $(window).on(‘mousewheel’, function() <>);
Источник