简体   繁体   中英

How do I remove the :hover state from a link using jquery?

I have a website with the following simplified menu code:

<li><a id='link1' class="menu active" href="javascript:doslide(1);">Item 1</a></li>
<li><a id='link2' class="menu" href="javascript:doslide(2);">Item 2</a></li>
<li><a id='link3' class="menu" href="javascript:doslide(3);">Item 3</a></li>
<li><a id='link4' class="menu" href="javascript:doslide(4);">Item 4</a></li>
<li><a id='link5' class="menu" href="javascript:doslide(5);">Item 5</a></li>

In my CSS, .menu:hover gives the menu links a different background colour, and .menu.active indicates the selected screen. doslide() is a javascript function for sliding screens in from the left or right based on location, and it works something like this:

var currentpanel = 1;
var numpanels = 5;
doslide = function(panelid) {
    if (panelid != currentpanel) {
        $('.menu').blur();
        $('.active').removeClass("active");
        $('#link'+panelid).addClass('active');
        . . .
}

I have also added a touchscreen swipe detector, so that in addition to using the menu to move between panels, you can swipe left and right to bring in the next screen. The point is to emulate the functionality of a mobile app.

My problem is that when I use this on my phone, if I tap a menu item to load that screen, and then swipe, the menu item I tapped on still has its :hover state. That means you can be on screen 3, but have the menu item for screen 2 highlighted as if you're holding a mouse over it. I thought that $('.menu').blur(); would fix this, but it doesn't. Is there a straightforward way to remove the :hover state from the link? I don't want to remove the mouseover effect entirely, just make the phone no longer think the menu item is being hovered over.

I've also tried having the menu links go to javascript:; and attaching events to them for click , to no avail. For the swipe, I have tried both methods below:

$('#panelholder').swipe({
    swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
        if (direction == 'left' && currentpanel < numpanels) {
            $('#link_'+(currentpanel+1)).click();
            // doslide(currentpanel+1);
        } else if (direction == 'right' && currentpanel > 1) {
            $('#link_'+(currentpanel-1)).click();
            // doslide(currentpanel-1);
        }
    }
});

I've also tried adding setTimeout(function() {$('body').click().trigger('tap');}, 50); to no avail.

Easiest way is to wrap your :hover css in a media query so it doesn't apply to mobile devices.

@media screen and (min-width: 1200px) { 
  myElement:hover {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM