4

我目前正在使用下面的代码,当用户将鼠标悬停在图像上时,使用 jQuery 和悬停功能淡入“标题”元素。这在桌面浏览器上非常有效,但是在使用 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>

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

克里斯

4

2 回答 2

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);
    });

});
于 2012-11-16T19:27:07.677 回答
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 是否为真,如果是,则执行您的操作。

于 2012-11-16T17:33:19.530 回答