如何在 javascript 中使用 DIV ID 对 DIV 产生悬停效果

How can I have hover effect on DIV's using the DIV ID in javascript?

本文关键字:DIV 悬停 ID javascript      更新时间:2023-09-26

我想使用div id 对每个div 有不同的悬停效果。可能吗?我已经在谷歌上搜索了一段时间,我看到的只是使用类名和标签的悬停效果。我想使用 javascript 或 jquery 来做到这一点。任何帮助不胜感激,谢谢!

您可以从函数中评估id

$(".hoverItems").hover( overState, outState );
function overState () {
  switch ( this.id ) {
    case "foo" :
      /* effect a */
      break;
    case "bar" :
      /* effect b */
  }
}
function outState () {
  switch ( this.id ) {
    case "foo" :
      /* undo effect a */
      break;
    case "bar" :
      /* undo effect b */
  }
}

演示:http://jsbin.com/evikog/edit#javascript,html

使用 JQuery,您可以将动作绑定到 mouseEvent :http://api.jquery.com/category/events/mouse-events/

你只需要将事件绑定到你的div并做你的动画......

$("#foo,#bar").hover( overState, outState );
function overState () {
      /* effect */
}
function outState () {
      /* undo effect */
}

如果要对多个div 进行动画处理,请将它们设置为一个类。例如"动画":

.HTML:

<div class="animated">blabla</div>

爪哇语

$(".animated").hover( overState, outState );

这样,所有带有动画类的div 都将具有动画。

您可以将 css 与 class+id 的组合用于特定样式