Javascript 将hover、onmouseetner、onmouseleave函数添加到css类、语法

Javascript 将hover、onmouseetner、onmouseleave函数添加到css类、语法,javascript,jquery,css,Javascript,Jquery,Css,我的基本语法有问题。 我想使用jquery选择CSS类中的所有元素, 然后在用户将鼠标悬停在项目上时添加一个操作 $(".item").hover(function(){$(this).fadeTo(100, .1)}); 是否可以为onmouseenter和onmouseleave分配不同的功能?查找类似的代码时有点困难。使用.hover(),可以传递两个函数 $(".item").hover( function(){$(this).fadeTo(100, .1)}, fun

我的基本语法有问题。 我想使用jquery选择CSS类中的所有元素, 然后在用户将鼠标悬停在项目上时添加一个操作

$(".item").hover(function(){$(this).fadeTo(100, .1)});
是否可以为onmouseenter和onmouseleave分配不同的功能?查找类似的代码时有点困难。

使用
.hover()
,可以传递两个函数

$(".item").hover(
    function(){$(this).fadeTo(100, .1)},
    function(){$(this).fadeTo(100, 1)}
);
这些将被分配为
mouseenter
mouseleave
事件


当然,你也可以手动操作

$(".item").mouseenter(function(){$(this).fadeTo(100, .1)})
          .mouseleave(function(){$(this).fadeTo(100, 1)});

或者您甚至可以重用相同的函数,只需测试事件对象

$(".item").hover(function(event){
    $(this).fadeTo(100, event.type === 'mouseenter' ? .1 : 1);
});
使用
.hover()
,可以传递两个函数

$(".item").hover(
    function(){$(this).fadeTo(100, .1)},
    function(){$(this).fadeTo(100, 1)}
);
这些将被分配为
mouseenter
mouseleave
事件


当然,你也可以手动操作

$(".item").mouseenter(function(){$(this).fadeTo(100, .1)})
          .mouseleave(function(){$(this).fadeTo(100, 1)});

或者您甚至可以重用相同的函数,只需测试事件对象

$(".item").hover(function(event){
    $(this).fadeTo(100, event.type === 'mouseenter' ? .1 : 1);
});

悬停
可以使用一个或两个事件处理程序。如果提供了一个(如您的示例中所示),它将应用于
mouseenter
mouseleave
事件。如果提供了两个,则每个事件都有自己的处理程序

更多信息请参阅

从您的示例来看,我假设您希望在
mouseleave
上淡入元素,如果是这样,请尝试以下操作:

$(".item").hover(
    function(){ $(this).fadeTo(100, .1) },
    function(){ $(this).fadeTo(100, 1)} ); 
);

悬停
可以使用一个或两个事件处理程序。如果提供了一个(如您的示例中所示),它将应用于
mouseenter
mouseleave
事件。如果提供了两个,则每个事件都有自己的处理程序

更多信息请参阅

从您的示例来看,我假设您希望在
mouseleave
上淡入元素,如果是这样,请尝试以下操作:

$(".item").hover(
    function(){ $(this).fadeTo(100, .1) },
    function(){ $(this).fadeTo(100, 1)} ); 
);
是的,这是可能的

$(".item").hover( function(){ /* onmouseenter */ }, function(){/* onmouseleave */} );
是的,这是可能的

$(".item").hover( function(){ /* onmouseenter */ }, function(){/* onmouseleave */} );