简体   繁体   中英

How can I add click events with JavaScript (or CSS) on iOS devices?

I'm having trouble with a hover technique I'm trying to implement on a site. Basically, I have div ( .portfolio-item ) which is used to display a background-image . The .portfolio-item contains one direct child — <div class="portfolio-item-info"> which is absolutely positioned and is only shown when the user hovers over the parent element.

This works fine on laptops and Android devices but for iOS devices it doesn't work at all. So if the user touches the .portfolio-item div, nothing happens.

HTML

<div class="portfolio-item" style="background-image: url('path/to/url')">
    <div class="portfolio-item-info">
        <h3 class="font-secondary-bold">Some Title</h3>
        <ul class="list-unstyled list-inline">
            <li>Publication</li>
            <li>Print</li>
        </ul>
        <a href="#">Take a look</a>
    </div>
</div>

CSS

.portfolio-item {
    background-color: #fff;
    background-size: cover;
    margin-bottom: 24px;
    overflow: hidden;
    position: relative;
    min-height: $portfolioItemHeight;

    &:before {
        content: "";
        background-color: $colorLight;
        background-color: rgba(255, 255, 255, 0.8);
        min-height: $portfolioItemHeight;
        opacity: 0;
        position: absolute;
        left: 0;
        right: 0;
        transition: opacity 0.5s ease-in-out;
    }

    &:hover,
    &:focus {

        &:before {
            opacity: 1;
        }

        .portfolio-item-info {
            top: 0;
        }
    }
}

To make it work I'm using something really hacky, I'm putting an onclick attribute on the .portfolio-item div eg

<div class="portfolio-item" onclick="void(0)" style="background-image: url('path/to/url')">

This hacky solution does work but I'd ideally like something less… hacky .

No standard defines how touch devices should deal with hover and it's up to the browser vendor, so any solution will be a kind of 'hack'. However, the following one is more reliable:

Using jQuery you can turn the class hover on / off on touch start / end

$(document).ready(function() {
    $('.portfolio-item').bind('touchstart touchend', function(e) {
        e.preventDefault();
        $(this).toggleClass('hover');
    });
});

In CSS you add the .hover class with the same parameters as existing :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