可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have some websites I built times ago, that use jquery mouse events...I just got an ipad and i noticed that all the mouse over events are translated in clicks...so for instance i have to do two clicks instead of one..(the first hover, than the actual click)
is there a workaround ready to solve this? maybe a jquery command i shoudl have used instead of mouseover/out etc..
thanks!
回答1:
Haven't tested this fully but since iOS fires touch events, this could work, assuming you are in a jQuery setting.
$('a').on('click touchend', function(e) {
var el = $(this);
var link = el.attr('href');
window.location = link;
});
The idea is that Mobile WebKit fires a touchend
event at the end of a tap so we listen for that and then redirect the browser as soon as a touchend
event has been fired on a link.
回答2:
It is not entirely clear what your question is, but if you just want to eliminate the double click, while retaining the hover effect for the mouse, my advice is to:
- Add hover effects on
touchstart
and mouseenter
.
- Remove hover effects on
mouseleave
, touchmove
and click
.
Background
In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com):
touchstart
touchmove
touchend
- 300ms delay, where the browser makes sure this is a single tap, not a double tap
mouseover
mouseenter
- Note: If a
mouseover
, mouseenter
or mousemove
event changes the page content, the following events are never fired.
mousemove
mousedown
mouseup
click
It does not seem possible to simply tell the webbrowser to skip the mouse events.
What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.
Solution Explained
To recap:
- Add hover effects on
touchstart
and mouseenter
.
- Remove hover effects on
mouseleave
, touchmove
and click
.
Note that there is no action on touchend
!
This clearly works for mouse events: mouseenter
and mouseleave
(slightly improved versions of mouseover
and mouseout
) are fired, and add and remove the hover.
If the user actually click
s a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.
This also works for touch events: on touchstart
the hover effect is added. It is '''not''' removed on touchend
. It is added again on mouseenter
, and since this causes no content changes (it was already added), the click
event is also fired, and the link is followed without the need for the user to click again!
The 300ms delay that a browser has between a touchstart
event and click
is actually put in good use because the hover effect will be shown during this short time.
If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave
event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove
.
That's it!
Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.
Alternative Solutions
I've found the following problems with the following alternatives:
- browser detection: Extremely prone to errors. Assumes that a device has either mouse or touch, while a combination of both will become more and more common when touch displays prolifirate.
- CSS media detection: The only CSS-only solution I'm aware of. Still prone to errors, and still assumes that a device has either mouse or touch, while both are possible.
- Emulate the click event in
touchend
: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.
- Use a variable to suppress mouse events: This set a variable in
touchend
that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend
is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).
Further Reading
- http://jsfiddle.net/macfreek/24Z5M/. Test the above solution for yourself in this sandbox.
- http://www.macfreek.nl/memory/Touch_and_mouse_with_hover_effects_in_a_web_browser. This same answer, with a bit more background.
- http://www.html5rocks.com/en/mobile/touchandmouse/. Great background article on html5rocks.com about touch and mouse in general.
- https://developer.apple.com/library/ios/DOCUMENTATION/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html. Safari Web Content Guide - Handling Events. See in particular figure 6.4, which explains that no further events are fired after a content change during a
mouseover
or mousemove
event.
See also iPad/iPhone double click problem and Disable hover effects on mobile browsers.
回答3:
Seems there is a CSS solution after all. The reason Safari waits for a second touch is because of the background image (or elements) you usually assign on the :hover event. If there is none to be shown - you won't have any problems. The solution is to target iOS platform with secondary CSS file (or style in case of a JS approach) which overrides :hover background to inherit for example and keep hidden the elements you were going to display on mouse over:
Here is an example CSS and HTML - a product block with a starred label on mouse over:
HTML:
<a href="#" class="s"><span class="s-star"></span>Some text here</a>
CSS:
.s {
background: url(some-image.png) no-repeat 0 0;
}
.s:hover {
background: url(some-image-r.png) no-repeat 0 0;
}
.s-star {
background: url(star.png) no-repeat 0 0;
height: 56px;
position: absolute;
width: 72px;
display:none;
}
.s:hover .s-star {
display:block;
}
Solution (secondary CSS):
/* CSS */
/* Keep hovers the same or hidden */
.s:hover {
background:inherit;
}
.s:hover .s-star {
display:none;
}
回答4:
What worked for me is what others here have already said:
Don't show/hide elements on hover or mousemove (which is the event in my case).
Here's what Apple says (https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html):
A clickable element is a link, form element, image map area, or any other element with mousemove, mousedown, mouseup, or onclick handlers
If the user taps a clickable element, events arrive in this order: mouseover, mousemove, mousedown, mouseup, and click. Also, if the contents of the page changes on the mousemove event, no subsequent events in the sequence are sent. This behavior allows the user to tap in the new content.
So, you could use @woop's solution: detect the userAgent, check if it's and iOS device and then bind the event. I ended up using this technique because it suits my needs and it makes more sense do not bind hover events when you don't want it.
But... if you don't wanna mess with userAgents and still hide/show elements on hover/mousemove, i found out you can do so by using native javascript, like this:
$("body").on("mouseover", function() {
document.getElementsByTagName("my-class")[0].style.display = 'block'; //show element
document.querySelector(".my-selector div").style.display = 'none'; // hide element
});
This will work on the Desktop version and will do nothing on the mobile version.
And for a little more compatibility...
$("body").on("mouseover", function() {
if (document.getElementsByTagName && document.querySelector) { // check compatibility
document.getElementsByTagName("my-class")[0].style.display = 'block'; //show element
document.querySelector(".my-selector div").style.display = 'none'; // hide element
} else {
$(".my-class").show();
$(".my-selector div").hide();
}
});
回答5:
No need to make overcomplicated.
$('a').on('touchend', function() {
$(this).click();
});
回答6:
cduruk's solution was quite effective, but caused problems on a few parts of my site. Because I was already using jQuery to add the CSS hover class, the easiest solution was to simply not add the CSS hover class on mobile devices (or more precisely, to ONLY add it when NOT on a mobile device).
Here was the general idea:
var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);
if (!(ios)) {
$(".portfolio-style").hover(
function(){
$(this).stop().animate({opacity: 1}, 100);
$(this).addClass("portfolio-red-text");
},
function(){
$(this).stop().animate({opacity: 0.85}, 100);
$(this).removeClass("portfolio-red-text");
}
);
}
*code reduced for illustrative purposes
回答7:
I think it'd be wise to try mouseenter
in place of mouseover
. It's what's used internally when binding to .hover(fn,fn)
and is generally what you want.
回答8:
I had the following problems with the existing solutions, and found something that seems to solve all of them. This assumes you're aiming for something cross browser, cross device, and don't want device sniffing.
The problems this solves
Using just touchstart
or touchend
:
- Causes the event to fire when people are trying to scroll past the content and just happened to have their finger over this element when they starting swiping - triggering the action unexpectedly.
- May cause the event to fire on longpress, similar to right click on desktop. For example, if your click event goes to URL X, and the user longpresses to open X in a new tab, the user will be confused to find X open in both tabs. On some browsers (e.g. iPhone) it may even prevent the long press menu from appearing.
Triggering mouseover
events on touchstart
and mouseout
on touchmove
has less serious consequences, but does interfere with the usual browser behaviour, for example:
- A long press would trigger a mouseover that never ends.
- Many Android browsers treat the location of the finger on
touchstart
like a mouseover
, which is mouseout
ed on the next touchstart
. One way to see mouseover content in Android is therefore to touch the area of interest and wiggle your finger, scrolling the page slightly. Treating touchmove
as mouseout
breaks this.
The solution
In theory, you could just add a flag with touchmove
, but iPhones trigger touchmove even if there's no movement. In theory, you could just compare the touchstart
and touchend
event pageX
and pageY
but on iPhones, there's no touchend
pageX
or pageY
.
So unfortunately to cover all bases it does end up a little more complicated.
$el.on('touchstart', function(e){
$el.data('tstartE', e);
if(event.originalEvent.targetTouches){
// store values, not reference, since touch obj will change
var touch = e.originalEvent.targetTouches[0];
$el.data('tstartT',{ clientX: touch.clientX, clientY: touch.clientY } );
}
});
$el.on('touchmove', function(e){
if(event.originalEvent.targetTouches){
$el.data('tstartM', event.originalEvent.targetTouches[0]);
}
});
$el.on('click touchend', function(e){
var oldE = $el.data('tstartE');
if( oldE && oldE.timeStamp + 1000 < e.timeStamp ) {
$el.data('tstartE',false);
return;
}
if( $el.data('iosTouchM') && $el.data('tstartT') ){
var start = $el.data('tstartT'), end = $el.data('tstartM');
if( start.clientX != end.clientX || start.clientY != end.clientY ){
$el.data('tstartT', false);
$el.data('tstartM', false);
$el.data('tstartE',false);
return;
}
}
$el.data('tstartE',false);
In theory, there are ways to get the exact time used for a longpress instead of just using 1000 as an approximation, but in practice it's not that simple and it's best to use a reasonable proxy.
回答9:
MacFreak's answer was extremely helpful to me. Here's some hands-on code in case it helps you.
PROBLEM - applying touchend means every time you scroll your finger over an element, it responds as if you've pressed it, even if you were just trying to scroll past.
I'm creating an effect with jQuery which fades up a line under some buttons to "highlight" the hovered button. I do not want this to mean you have to press the button twice on touch devices to follow the link.
Here are the buttons:
<a class="menu_button" href="#">
<div class="menu_underline"></div>
</a>
I want the "menu_underline" div to fade up on mouseover and fade out on mouseout. BUT I want touch devices to be able to follow the link on one single click, not two.
SOLUTION - Here's the jQuery to make it work:
//Mouse Enter
$('.menu_button').bind('touchstart mouseenter', function(){
$(this).find(".menu_underline").fadeIn();
});
//Mouse Out
$('.menu_button').bind('mouseleave touchmove click', function(){
$(this).find(".menu_underline").fadeOut();
});
Many thanks for your help on this MacFreak.
回答10:
I just found out that it works if you add an empty listener, don't ask me why, but I tested it on iPhone and iPad with iOS 9.3.2 and it worked fine.
if(/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream){
var elements = document.getElementsByTagName('a');
for(var i = 0; i < elements.length; i++){
elements[i].addEventListener('touchend',function(){});
}
}
回答11:
I "think" that your links have no onmouseover event, where 1 tap activates onmouseover and the double tap activates the link. but idk. I don't have an iPad.
I think ya gotta use gesture/touch events.
https://developer.apple.com/documentation/webkitjs
回答12:
I had the same problem but not on a touch device. The event triggers every time you click. There is something about event queuing or so.
However, my solution was like this:
On click event (or touch?) you set a timer. If the link is clicked again within X ms, you just return false.
To set per element timer, you can use $.data()
.
This also may fix the @Ferdy problem described above.
回答13:
If you use Modernizr, it is very easy to use Modernizr.touch as mentioned earlier.
However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
function Tipsy(element, options) {
this.$element = $(element);
this.options = options;
this.enabled = !isTouchDevice;
this.fixTitle();
};
If you don't use Modernizr, you can simply replace the Modernizr.touch
function above with ('ontouchstart' in document.documentElement)
Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone.
回答14:
You can use click touchend
,
example:
$('a').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
Above example will affect all links on touch devices.
If you want to target only specific links, you can do this by setting a class on them, ie:
HTML:
<a href="example.html" class="prevent-extra-click">Prevent extra click on touch device</a>
Jquery:
$('a.prevent-extra-click').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
Cheers,
Jeroen
回答15:
I ran into a similar situation where I had events binded to the mouseenter/mouseleave/click states of an element, yet on an iPhone, the user had to double click the element to first trigger the mouseenter event, then again to fire the click event.
I resolved this using a similar method as above, but I made use of the jQuery $.browser plugin (for jQuery 1.9>) and added a .trigger event to the mouseenter binding event, as follows:
// mouseenter event
$('.element').on( "mouseenter", function() {
// insert mouseenter events below
// double click fix for iOS and mouseenter events
if ($.browser.iphone || $.browser.ipad) $(this).trigger('click');
});
// mouseleave event
$('.element').on( "mouseleave", function() {
// insert mouseout events below
});
// onclick event
$('.element').on( "click", function() {
// insert click events below
});
The .trigger prevents the need to double click the element by firing the .click event handler upon mouseenter (or initial click) of the element when viewed on iPhones or iPads. Might not be the most elegant solution, but it works great in my case and utilizes a plugin that I already had in place, and required me to add a single line of code to get my existing events working under these devices.
You can get the jQuery $.browser plugin here: https://github.com/gabceb/jquery-browser-plugin
回答16:
Just an improvement to avoid redirection when you slide your finger on a link by mistake.
// tablet "one touch (click)" X "hover" > link redirection
$('a').on('touchmove touchend', function(e) {
// if touchmove>touchend, set the data() for this element to true. then leave touchmove & let touchend fail(data=true) redirection
if (e.type == 'touchmove') {
$.data(this, "touchmove_cancel_redirection", true );
return;
}
// if it's a simple touchend, data() for this element doesn't exist.
if (e.type == 'touchend' && !$.data(this, "touchmove_cancel_redirection")) {
var el = $(this);
var link = el.attr('href');
window.location = link;
}
// if touchmove>touchend, to be redirected on a future simple touchend for this element
$.data(this, "touchmove_cancel_redirection", false );
});
回答17:
With inspiration from MacFreak, I put together something that works for me.
This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks in some cases. In CSS, if you have any :hover psudo classes in your css, change them to .hover For example .some-class:hover to .some-class.hover
Test this code on an ipad to see how css and js hover method behave differently (in hover effect only). The CSS button doesn't have a fancy click alert.
http://jsfiddle.net/bensontrent/ctgr6stm/
function clicker(id, doStuff) {
id.on('touchstart', function(e) {
id.addClass('hover');
}).on('touchmove', function(e) {
id.removeClass('hover');
}).mouseenter(function(e) {
id.addClass('hover');
}).mouseleave(function(e) {
id.removeClass('hover');
}).click(function(e) {
id.removeClass('hover');
//It's clicked. Do Something
doStuff(id);
});
}
function doStuff(id) {
//Do Stuff
$('#clicked-alert').fadeIn(function() {
$(this).fadeOut();
});
}
clicker($('#unique-id'), doStuff);
button {
display: block;
margin: 20px;
padding: 10px;
-webkit-appearance: none;
touch-action: manipulation;
}
.hover {
background: yellow;
}
.btn:active {
background: red;
}
.cssonly:hover {
background: yellow;
}
.cssonly:active {
background: red;
}
#clicked-alert {
display: none;
}
<button id="unique-id" class="btn">JS Hover for Mobile devices<span id="clicked-alert"> Clicked</span>
</button>
<button class="cssonly">CSS Only Button</button>
<br>This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks. In CSS, if you have any :hover in your css, change them to .hover For example .some-class:hover to .some-class.hover
回答18:
To get the links working without breaking touch scrolling, I solved this with jQuery Mobile's "tap" event:
$('a').not('nav.navbar a').on("tap", function () {
var link = $(this).attr('href');
if (typeof link !== 'undefined') {
window.location = link;
}
});
回答19:
I am too late, I know but this is one of the easiest workaround I've found:
$('body').on('touchstart','*',function(){ //listen to touch
var jQueryElement=$(this);
var element = jQueryElement.get(0); // find tapped HTML element
if(!element.click){
var eventObj = document.createEvent('MouseEvents');
eventObj.initEvent('click',true,true);
element.dispatchEvent(eventObj);
}
});
This does not only works for links(anchor tags) but for other elements also. Hope this helps.
回答20:
This short snippet seems to work.
Trigger the click event when link tapped :
$('a').on('touchstart', function() {
$(this).trigger('click');
});
回答21:
None from the other answer works for me. My app has a lot of event listeners, own checkboxes and links that has listener's and links without listener's.
I use this:
var selector = "label, a, button";
var timer;
var startX;
var startY;
$(document).on("click", selector, function (e) {
if ($(this).data("touched") === true) {
e.stopImmediatePropagation();
return false;
}
return;
}).on("touchend", selector, function (e) {
if (Math.abs(startX - e.originalEvent.changedTouches[0].screenX) > 10 || Math.abs(startY - e.originalEvent.changedTouches[0].screenY) > 10)
// user action is not a tap
return;
var $this = $(this);
// Visit: http://stackoverflow.com/questions/1694595/can-i-call-jquery-click-to-follow-an-a-link-if-i-havent-bound-an-event-hand/12801548#12801548
this.click();
// prevents double click
$this.data("touched", true);
if (timer)
clearTimeout(timer);
setTimeout(function () {
$this.data("touched", false);
}, 400);
e.stopImmediatePropagation();
return false;
}).on("touchstart", function (e) {
startX = e.originalEvent.changedTouches[0].screenX;
startY = e.originalEvent.changedTouches[0].screenY;
});
回答22:
This works for me when you have jquery ui dropdown
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
$('.ui-autocomplete').off('menufocus hover mouseover');
}
回答23:
Avoid changing of "display" style inside of hover css event. I had "display: block" in hover state. After removing ios went on lins by single tap. By the way it seems that latest IOS updates fixed this "feature"
回答24:
You could check navigator.userAgent
like this:
if(!navigator.userAgent.match(/iPhone/i) || !navigator.userAgent.match(/iPad/i)) {
//bind your mouseovers...
}
but you would have to check for blackberries, droids, umpty other touchscreen devices. You could also bind the mouseovers only if the userAgent contains Mozilla, IE, Webkit, or Opera, but you still need to screen for some devices because the Droid, for instance, reports its userAgent string as:
Mozilla/5.0 (Linux; U; Android 2.0.1; en-us; Droid Build/ESD56) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17
The iPhone's string is similar. If you just screen for iPhone, iPod, iPad, Android and Blackberry you might get the majority of handhelds, but not all of them.
回答25:
Simply make a CSS media query which excludes tablets and mobile devices and put the hover in there. You don't really need jQuery or JavaScript for this.
@media screen and (min-device-width:1024px) {
your-element:hover {
/* Do whatever here */
}
}
And be sure to add this to your html head to make sure that it calculates with the actual pixels and not the resolution.
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />