在触摸屏上保留悬停效果

Preserve hover effect on touchscreen

我正在使用 Instsfeed.js 开发一个包含图像提要的网站。拉取图片、点赞、评论,一切正常。

我制作了一个悬停效果,在图片上叠加点赞和评论的数量,如下所示:https://jsfiddle.net/9w1neq9m/3/

#instafeed {
  margin-top: 30px;
  text-align: center;
  font-family: 'brandon-grotesque', sans-serif;
}
.insta-post {
  display: inline-block;
  margin: 0 10px 20px 10px;
  position: relative;
}
.insta-hover {
  position: absolute;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background: rgba(0, 0, 0, .5);
  color: white;
  opacity: 0;
  transition: opacity 1s;
  -webkit-transition: opacity 1s;
  padding: 0 15px;
}
.insta-hover .fa:last-of-type {
  padding-left: 15px
}
.insta-post:hover .insta-hover {
  opacity: 1;
  transition: opacity 1s;
  -webkit-transition: opacity 1s;
}
<div id="instafeed">
  <div class="insta-post">
    <a href="#" target="_blank">
      <div class="insta-hover">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut quam libero, blandit at odio et, fermentum luctus massa. Sed et tortor volutpat, semper orci sit amet, venenatis metus. Nullam scelerisque sem at risus maximus sodales.</p>
        <p><i class="fa fa-heart" aria-hidden="true"></i> 130 <i class="fa fa-comment" aria-hidden="true"></i> 29</p>
      </div>
      <img src="https://unsplash.it/300/300" alt="Image from Instagram">
    </a>
  </div>

  <div class="insta-post">
    <a href="#" target="_blank">
      <div class="insta-hover">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut quam libero, blandit at odio et, fermentum luctus massa. Sed et tortor volutpat, semper orci sit amet, venenatis metus. Nullam scelerisque sem at risus maximus sodales.</p>
        <p><i class="fa fa-heart" aria-hidden="true"></i> 130 <i class="fa fa-comment" aria-hidden="true"></i> 29</p>
      </div>
      <img src="https://unsplash.it/300/300" alt="Image from Instagram">
    </a>
  </div>
</div>

显然这不适用于移动设备。轻按直接进入 link(如您所料..)但这并不是我真正想要的。

我想先点按以激活悬停效果,然后,如果用户再次点按,link 才能真正起作用。

我发现这个 http://www.hnldesign.nl/work/code/mouseover-hover-on-touch-devices-using-jquery/ 似乎完全符合我的要求 - 我就是无法让它工作。整个 hide/show 悬停的事情让我失望了..

给你:

jQuery:

$('.insta-post').on("touchstart", function(e) {
  "use strict"; //satisfy the code inspectors
  var link = $(this); //preselect the link
  if (link.hasClass('hasHover')) {
    return true;
  } else {
    link.addClass("hasHover");
    $('.insta-post').not(this).removeClass("hasHover");
    e.preventDefault();
    return false; //extra, and to make sure the function has consistent return points
  }
});

CSS:

.insta-post:hover .insta-hover,
.insta-post.hasHover .insta-hover {
  opacity: 1;
  transition: opacity 1s;
  -webkit-transition: opacity 1s;
}

已更新JSFiddle

Visit it using a touch device, or using debug tools like Chrome’s web inspector, which can simulate touch.


PS: thanks a lot for sharing such useful link as I really need this kind of plugin.