How do I simulate a hover with a touch in touch enabled browsers?

后端 未结 14 2052
旧巷少年郎
旧巷少年郎 2020-11-22 17:04

With some HTML like this:

Some Text

Then some CSS like this:

p {
  color:black;
}

p:hover {
  color:red         


        
14条回答
  •  孤独总比滥情好
    2020-11-22 17:33

    Add this code and then set class "tapHover" to elements which you would like to work this way. First time you tap an element it will gain pseudoclass ":hover" and class "tapped". Click event will be prevented. Second time you tap the same element - click event will be fired.

    // Activate only in devices with touch screen
    if('ontouchstart' in window)
    {
        // this will make touch event add hover pseudoclass
        document.addEventListener('touchstart', function(e) {}, true);
    
        // modify click event
        document.addEventListener('click', function(e) {
            // get .tapHover element under cursor
            var el = jQuery(e.target).hasClass('tapHover')
                ? jQuery(e.target)
                : jQuery(e.target).closest('.tapHover');
    
            if(!el.length)
                return;
    
            // remove tapped class from old ones
            jQuery('.tapHover.tapped').each(function() {
                if(this != el.get(0))
                    jQuery(this).removeClass('tapped');
            });
    
            if(!el.hasClass('tapped'))
            {
                // this is the first tap
                el.addClass('tapped');
                e.preventDefault();
                return false;
            }
            else
            {
                // second tap
                return true;
            }
        }, true);
    }
    .box {
    	float:		left;
    	
    	display:	inline-block;
    	margin:		50px 0 0 50px;
    	width:		100px;
    	height:		100px;
    	overflow:	hidden;
    	
    	font-size:	20px;
    	
    	border:		solid 1px black;
    }
    .box.tapHover {
    	background:	yellow;
    }
    .box.tapped {
    	border:		solid 3px red;
    }
    .box:hover {
    	background:	red;
    }

提交回复
热议问题