Jquery/CSS:如何在mouseenter事件上应用延迟1秒的addClass

Jquery/CSS: How to apply addClass with a delay of 1 sec on mouseenter event.

本文关键字:应用 延迟 1秒 addClass 事件 mouseenter CSS Jquery      更新时间:2023-09-26

这是我的addClass代码,它正在工作。但当我尝试使用延迟或setTimeout函数时,它不起作用。

我不想在CSS中使用webkit属性。

如果有人早些时候遇到这个问题,请告知。

  $(document).ready(function(){
          $('#table_Id tr td').mouseenter(function(){ 
               $(this).parent('tr').addClass('blueBgColor'); 
            });
  });

使用setTimeout,它会在指定的延迟后调用函数或执行代码段。

$(document).ready(function() {
    $('#table_Id tr td').mouseenter(function() {
        var self = this; //Cache this in a variable
        setTimeout(function() {
            $(self).parent('tr').addClass('blueBgColor');
        }, 1000); //Here delay in milliseconds
    });
});

EDIT:bind 的使用

$(document).ready(function() {
    $('#table_Id tr td').mouseenter(function() {
        setTimeout(function() {
            $(this).parent('tr').addClass('blueBgColor');
        }.bind(this), 1000); //Here delay in milliseconds
    });
});

嘿,我为你的问题创建了一个jsfiddle。。。

代码:-

 $(document).ready(function() {
     $('#table_Id tr td').mouseenter(function() {
         var td = $(this);
         setTimeout(function() {
             td.parent('tr').addClass('blueBgColor');
         }, 1000);
     });
 });

工作示例:-

http://jsfiddle.net/L7S37/14/

感谢

$(document).ready(function(){
  var myTimeout;
  $('#table_Id tr td').on("mouseenter", function(){
    var that = $(this);
    myTimeout = setTimeout(function () {
      that.parent('tr').addClass('blueBgColor');
    }, 1000);
  });
  // Also if you need, you can do:
  $('#table_Id tr td').on("mouseleave", function(){
    clearTimeout(myTimeout);
  });
});

OR:

$(document).ready(function(){
  var myTimeout;
  // use event.target
  $('#table_Id tr td').on("mouseenter", function (e) {
    myTimeout = setTimeout(function () {
      $(e.target).parent('tr').addClass('blueBgColor');
    }, 1000);
  });
});

如果不存在toggle类,您可能需要使用它,否则在每个鼠标输入上,该类都会被反复添加:

$('#table_Id tr td').mouseenter(function(){
    $td = $(this);
    setTimeout(function(){$td.toggleClass('addedClass',true)},'1000');
});

js fiddle示例

试试这个

 $('#table_Id tr td').mouseenter(function(){
    var $this = $(this); 
    setTimeout(function () {
           $this.parent('tr').addClass('blueBgColor');        
   }, 1000);
});

试试这个

$('#table_Id tr td').off('mouseenter').on('mouseenter', function() {
    var element = this;
    setTimeout(function() {
        $(element).parent('tr').addClass('blueBgColor');
    }, 1000); /*delay for 1 sec*/
});