【问题标题】:jQuery: fadeIn / fadeOut on hover - alternatives on mobile devices?jQuery:悬停时的淡入/淡出 - 移动设备上的替代品?
【发布时间】:2017-08-10 15:30:23
【问题描述】:

我在 jQuery 中使用了 fadeIn 和 fadeOut,它在桌面上运行良好。但是,在移动设备上(我只在 iPhone 上测试过),子 div 在触摸时打开,但在触摸外部元素后不会隐藏。我对 jQuery 相当陌生,所以我不太确定我可以在这里实现什么样的解决方案。也许移动检测并执行触摸以打开/隐藏,尽管我不知道如何做到这一点。这是我的 JSFiddle:

https://jsfiddle.net/9LL3mmzt/

jQuery:

$(document).ready(function() {
  $(".parent").hover(function() {
    $(this).children(".child").fadeIn("fast");
  }, function() {
    $(this).children(".child").fadeOut("fast");
  });
});

HTML:

<div class="parent">
  <span>Peek-A-</span>
  <div class="child">
    <span>Boo</span>
  </div>
</div>

CSS:

.child {
  display: none;
}

我尝试了这个帖子的第一个解决方案:time-out on jQuery hover function

但是,由于我的知识有限,我无法使其正常工作。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    悬停功能并不是您真正应该在触控设备上使用的功能。我认为您需要检查一下 touchstart 功能。

    编辑 1: 一个例子是这样的:

    $('div.example').on("touchstart", function (e) {
        alert('testing');
    });
    

    但请记住,您仍然可以使用悬停 javascript,但您必须指定仅在非触摸设备上使用它。请参阅Modernizr

    希望这会有所帮助。

    仅供参考@James Douglas,正如您所见,由于我的声誉得分,我还不能发布任何 cmets。如果可能,请发表评论或帮助我们找到这个问题的答案,我认为这会更有用。

    编辑 2:Modernizr 非常方便。在您的情况下,您可以获得类触摸或非触摸(在 html 元素上),具体取决于您使用的设备。

    所以在我的示例中,您可以将其用作 $('.touch div.example')...

    可能有不同的解决方案,但我认为这是最好的方法(另见What's the best way to detect a 'touch screen' device using JavaScript?)。您只需将 demodernizr.js 文件添加到您的网站(最好在您的网页头部)。

    编辑 3:我已经在 iPhone 和 Android 上测试了你的 jsfiddle 示例,它可以工作。所以对我来说这是一件好事。

    【讨论】:

    • 如果您想详细说明一下,请编辑您的答案。如果没有,您应该将其作为评论发布。
    • @Nick 举个例子就好了!
    • @Nick,是否可以只使用 if/else 语句而不是使用 Modernizr?好像太复杂了。
    • @Nick,我使用您的示例和我在 OP 中链接的线程中的解决方案合并了这个解决方案:jsfiddle.net/tkeaoffd 它至少在 iPhone 上工作正常,这个解决方案是否合理?
    【解决方案2】:

    我能够使用@Nick 帖子中的示例和我在 OP 中链接的线程中的解决方案来完成这项工作(至少在 iPhone 上):

    这是 JSFiddle:https://jsfiddle.net/tkeaoffd/

    JQuery:

    $(document).ready(function() {
      function hasTouch() {
        try {
          document.createEvent("TouchEvent");
          return (true);
        } catch (e) {
          return (false);
        }
      }
      var touchPresent = hasTouch();
      $('.parent').hover(function() {
        var caption = $(this).find('.child');
        caption.stop(true, true).fadeIn("fast");
        if (touchPresent) {
          $('.parent').on("touchstart", function(e) {
            $(this).children(".child").fadeToggle("fast");
          });
        }
      }, function() {
        $(this).find('.child').stop(true, true).fadeOut("fast");
      });
    });
    

    HTML/CSS:

    <div class="parent">
      <span>Peek-A-</span>
      <div class="child">
        <span>Boo</span>
      </div>
    </div>
    
    
    .child {
      display: none;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      相关资源
      最近更新 更多