jQuery的悬停功能超时(time-out on jQuery hover function)

2019-07-03 21:10发布

我目前使用下面使用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>

任何想法,想法将是非常赞赏。

克里斯

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

});


Answer 2:

您可以使用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公司是真实的,如果是则做你的事。



文章来源: time-out on jQuery hover function
标签: jquery ios hover