【问题标题】:Hover event, but not on touch/mobile devices悬停事件,但不在触摸/移动设备上
【发布时间】:2019-11-25 13:34:30
【问题描述】:

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

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

这是我正在使用的。

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


    【解决方案1】:

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

    <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

    【讨论】:

      【解决方案2】:

      来自@PaulOB 在站点点

      <script>
        if (!("ontouchstart" in document.documentElement)) {
            $("#test-parent").hover(function() {
             $("#test-child").fadeToggle();
          });
         } 
      </script>
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 1970-01-01
        • 2013-10-22
        • 2014-04-28
        • 2020-12-09
        • 1970-01-01
        • 2023-03-18
        • 2019-04-03
        相关资源
        最近更新 更多