使元素的悬停效果只持续有限的时间

Make hover effect on element last only limited time

本文关键字:时间 元素 悬停      更新时间:2023-09-26

在我的笔:http://codepen.io/explicit_concept/pen/BLgoVG有一个脚本,触发规模/背景颜色的变化。icon元素只在整个。devicediv的第一次悬停。如何使效果是触发悬停仅持续3秒,例如?

我已经看到它是由doTimeout jQuery插件完成的,但为了学习,我想从头开始。

是否应该在鼠标悬停时使用setTimeout来添加类到元素中,然后当计时器完成时撤消。addclass ?

这是hover的jQuery代码:

$(document).ready(function () {
$('.device').one('mouseenter',function() {
  $(this).find('.icon').addClass('icon-hovered');
    });
$('.device').mouseleave(function() {
  $('.icon').removeClass('icon-hovered');
    });

setTimeout(() => {
    $(this).find(".icon").removeClass("icon-hovered")
}, 3000); // time in milliseconds

在您的mouseenter监听器将工作

jsFiddle: https://jsfiddle.net/wxmc3qks/1/

mouseleave事件上只使用javascript函数setTimeout。jQuery的delay函数只用于动画延迟,没有函数。

$(function() {
  $('.button').on('mouseenter', function() {
    $(this).addClass('hovered');
  });
  $('.button').on('mouseleave', function() {
    var $this = $(this);
    setTimeout(function() {
      $this.removeClass('hovered');
    }, 3000);
  });
});