2017-04-10 40 views
0

我想在悬停元素时执行代码。当指针消失时,我不想发生任何事情。此代码正是我想要的:仅在mouseover(或mouseout)上执行代码的最佳做法

$('li').hover(function() { 
    // actions here 
}, 
function() { 
}); 

$('ul').hover(function() { 
}, 
function() { 
    // other actions here 
}); 

但它很丑。我期待这个版本的清洁工作:

$('li').mouseover(function() { 
    // actions here 
}); 

$('ul').mouseout(function() { 
    // other actions here 
}); 

但事实并非如此。当我将指针移到元素上时,mouseover部分继续发射,而不是一次发射。

有什么建议吗?

+0

使用标志,并设置时它在第一次启动后会变成假。 –

+0

当悬停任何li元素时,我会显示一个背景图像(与每个li元素关联)。当悬停在整个列表中时,我想切换回默认的背景图像。当悬停在li元素之间时,我不想切换到默认图像。 – drake035

回答

0

添加活动类li你进入....删除所有活动类离开ul

$('li').mouseenter(function(){ 
    $(this).addClass('active'); 
}); 

$('ul').mouseleave(function(){ 
    $(this).find('.active').removeClass('active'); 
}) 
0

你可能想利用event delegation

像这样的东西应该工作:

$('ul').on('mouseover', 'li', function() { console.log('hovered'); });

0

鼠标悬停部分不断射击,我提出我的鼠标指针移到元素, 而不是发射一次。

您可以使用标志只执行一次代码块,但是,这不会阻止多次重新触发事件,它只会忽略第一个事件之后的事件。

var flag = true; 
$('li').mouseover(function() { 
    if(flag){ 

    // actions here 
    flag = false; 
    } 
}); 

虽然,我会建议您调查.mouseenter()

片段

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"> 
 
    </script> 
 
    </head> 
 
    <body> 
 
    <ul> 
 
     <li>list item</li> 
 
     <li>list item</li> 
 
     <li>list item</li> 
 
     <li>list item</li> 
 
     <li>list item</li> 
 
    </ul> 
 

 
    <script> 
 
     var flag = true; 
 
     $('li').mouseover(function() { 
 
     if(flag){ 
 
      console.log("testing"); 
 
      // actions here 
 
      flag = false; 
 
     } 
 
    }); 
 

 
    $('ul').mouseout(function() { 
 
    // other actions here 
 
    }); 
 

 
    </script> 
 
</body> 
 
</html>