悬停事件,但不在触摸/移动设备上

问题描述 投票:0回答:2

我正在尝试创建一个显示图像的悬停事件。在我的台式机/笔记本电脑上,它可以正确启动。但是,在移动设备(触摸屏)上,仅当单击模式链接时才会显示图像,然后该图像是粘性的(保持在屏幕上)。

在移动或触摸屏上,我不希望触发悬停事件。

这是我正在使用的东西。

Jsfiddle

HTML

<a href="#test" id="test-parent">Hover to show image</a>

<img class="preview" id="test-child" src="https://mayvers.com.au/wp-content/uploads/2017/09/test-image.jpg" />

<script>
  $("#test-parent").hover(function() {
    $("#test-child").fadeToggle();
  });
</script>

CSS

.preview {
  display: none;
  position: absolute;
  bottom: 0;
  right: 0;
  z-index: 1;
  height: 50%;
}
jquery hover jquery-hover
2个回答
0
投票

您可以检查是否为触摸事件,并相应地触发悬停效果。

<script>
  $("#test-parent").hover(function() {
   if(!isTouchEvent()){
    $("#test-child").fadeToggle();
   }
  });

  function isTouchEvent() {
    return 'ontouchstart' in document.documentElement
           || navigator.maxTouchPoints > 0
           || navigator.msMaxTouchPoints > 0;
  }

</script>

JSFiddle Demo


0
投票

从@PaulOB在现场点开始

<script>
  if (!("ontouchstart" in document.documentElement)) {
      $("#test-parent").hover(function() {
       $("#test-child").fadeToggle();
    });
   } 
</script>
© www.soinside.com 2019 - 2024. All rights reserved.