我正在使用下面的代码使用jQuery和hover函数在用户将鼠标悬停在图像上时淡入'caption'元素。这在桌面浏览器上非常有效,但是当使用移动触摸设备(如iPad)对其进行测试时,需要用户点击图像来触发悬停功能,标题会按预期淡入,但在用户选择页面上的其他对象之前保持活动状态。
我想知道一种简单的方法来修改我的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 :(得分:1)
您可以检测具有特征检测功能的触摸设备,然后相应地使用延时fadeOut()
调整您的行为:
$(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);
});
});
答案 1 :(得分: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是否为真,如果是,那么就做你的事。