2012-11-16 158 views
4

我目前正在使用下面的代码使用jQuery和悬停函数来淡入当用户悬停在图像上的'标题'元素。这在桌面浏览器上完美运行,但是当使用iPad等移动触摸设备进行测试时,需要用户点击图像以触发悬停功能,字幕按预期淡入,但保持活动状态,直到用户在页面上选择另一个对象。超时jQuery悬停功能

我想知道一个简单的方法来修改我的javascript代码来检测移动触摸设备,然后把一些排序或计时器的标题,以便它在一段时间后自动淡化?

<!-- include jQuery library --> 
<script type="text/javascript" src="./_js/jquery.min.js"></script> 
<script type="text/javascript"> 

$(document).ready(function() { 

    //On mouse over those thumbnail 
    $('.item-caption').hover(function() { 

     //Display the caption 
    $(this).find('.caption').stop(false,true).fadeIn(200); 
    }, 
    function() {  

    //Hide the caption 
    $(this).find('.caption').stop(false,true).fadeOut(600); 
}); 

}); 
</script> 

</head> 
<body> 

    <div class="item-caption"><a href="http://www.domain.com"> 
     <div class="caption"> 
      <ul> 
       <li><h2>TITLE</h2></li> 
       <li><h3>Description</h3></li> 
      </ul>  
     </div> 
     <img src="./_img/example_image.jpg"></a> 
    </div> 

</body> 

任何想法,想法将不胜感激。

克里斯

回答

0

可以使用navigator.userAgent.match来检测移动设备如下:

onMobile = false; 
// Mobile device detect - terrible, yes, but whatever 
if(navigator.userAgent.match(/Android/i) || 
navigator.userAgent.match(/webOS/i) || 
navigator.userAgent.match(/iPhone/i) || 
navigator.userAgent.match(/iPod/i) || 
navigator.userAgent.match(/iPad/i) || 
navigator.userAgent.match(/Blackberry/i) 
){ 
onMobile = true;     
} 

现在,在您的document.ready或任何你想要 - 检查是否OnMobile公司的真实,如果它是那么做你的事情。

+0

用户代理检测是一个可怕的想法 - 特征检测几乎总是一个更好的方式去。如果您想要检测触摸行为,则可以在Touch上使用功能检测。有关信息,请参阅http://stackoverflow.com/questions/4643443/how-do-i-detect-whether-a-browser-supports-mouseover-events。 – jfriend00

1

您可以检测到触摸设备与特征检测,然后用相应地调整你的行为一时间延迟​​:

$(document).ready(function() { 

    function hasTouch() { 
     try { 
      document.createEvent("TouchEvent"); 
      return(true); 
     } catch (e) { 
      return(false); 
     }  
    } 
    var touchPresent = hasTouch(); 

    //On mouse over those thumbnail 
    $('.item-caption').hover(function() { 

     //Display the caption 
     var caption = $(this).find('.caption'); 
     caption.stop(true, true).fadeIn(200); 
     // on touch systems, fade out after a time delay 
     if (touchPresent) { 
      caption.delay(5000).fadeOut(600); 
     } 
    }, function() {  

     //Hide the caption 
     $(this).find('.caption').stop(true, true).fadeOut(600); 
    }); 

}); 
+0

非常感谢您的意见jfriend00,完美的作品。一个问题,但。在我的HTML中,我在'item_caption'div中有一个url链接。这个链接可以和鼠标一起工作,因为用户必须首先将鼠标悬停在图片上,然后点击激活url.Hoverer – user1741348

+0

@ user1741348 - 我不明白你的问题。你想要链接的行为在触摸系统上? – jfriend00

+0

道歉意外地发送了一半的评论。在触摸设备上,用户触摸以触发悬停动作并显示标题,然后他们必须再次触摸以转到url。所有按预期工作,除非用户触摸,然后什么都不做,定时延迟开始并且字幕再次消失(如预期的那样)。然而,你会希望'悬停'功能现在被重置,但如果用户再次触摸而不是字幕再次消失,则URL正在激活。 – user1741348