Fix CSS hover on iPhone/iPad/iPod

2019-01-17 00:34发布

I want to fix the hover effect on iOS ( change to touch event ) but I dont have any idea . Let me explain this . You have a text in your page :

<div class="mm">hello world</div>

With style :

.mm { color:#000; padding:15px; }
.mm:hover { background:#ddd; }

Ok , in dekstop if you put your mouse over the text you get a #ddd background , right ? But in iOS if you touch the text you get nothing but if you tap it it gets a ugly and sticky #ddd background which is not nice and I want the user get the hover effect when he touch that text ( something like touchevent I think ) . But I see some websites fixed that like freemyappps.com or ( please check this site ->D4F on your ios device and touch something to see the hover effect like eating a cake :) ) But how these sites fixed that ? How can fix like them ? Thanks

14条回答
疯言疯语
2楼-- · 2019-01-17 01:00

Here is a basic, successful use of javascript hover on ios that I made:

Note: I used jQuery, which is hopefully ok for you.

JavaScript:

$(document).ready(function(){
  // Sorry about bad spacing. Also...this is jquery if you didn't notice allready.
  $(".mm").hover(function(){
    //On Hover - Works on ios
    $("p").hide();
  }, function(){
    //Hover Off - Hover off doesn't seem to work on iOS
    $("p").show();
 })
});

CSS:

.mm { color:#000; padding:15px; }

HTML:

<div class="mm">hello world</div>
<p>this will disappear on hover of hello world</p>
查看更多
甜甜的少女心
3楼-- · 2019-01-17 01:05

I"m not sure if this will have a huge impact on performance but this has done the trick for me in the past:

var mobileHover = function () {
    $('*').on('touchstart', function () {
        $(this).trigger('hover');
    }).on('touchend', function () {
        $(this).trigger('hover');
    });
};

mobileHover();
查看更多
你好瞎i
4楼-- · 2019-01-17 01:06

I successfully used

(function(l){var i,s={touchend:function(){}};for(i in s)l.addEventListener(i,s)})(document);

which was documented on http://fofwebdesign.co.uk/template/_testing/ios-sticky-hover-fix.htm

so a variation of Andrew M answer.

查看更多
Emotional °昔
5楼-- · 2019-01-17 01:09

The hover pseudo class only functions on iOS when applied to a link tag. They do that because there is no hover on a touch device reall. It acts more like the active class. So they can't have one unless its a link going somewhere for usability reasons. Change your div to a link tag and you will have no problem.

查看更多
该账号已被封号
6楼-- · 2019-01-17 01:10

In response to Dan (https://stackoverflow.com/a/20048559/4298604), I would recommend a slightly altered version.

<div onclick="void(0)">Click Me!</div>

Adding "void(0)" helps to obtain the undefined primitive value, as opposed to "".

查看更多
成全新的幸福
7楼-- · 2019-01-17 01:14

Some people don't know about this. You can apply it on div:hover and working on iPhone .

Add the following css to the element with :hover effect

.mm {
    cursor: pointer;
}
查看更多
登录 后发表回答