最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I add a hover class to an element? - Stack Overflow

programmeradmin3浏览0评论

In my CSS I have:

li.sort:hover {color: #F00;}

All my LI elements under the sort class function properly when the DOM is ready.

If I create a new LI element (using mootools el.addClass(classname)) I can set the base class, but can't figure out how to add a hover class to it.

Any ideas?

In my CSS I have:

li.sort:hover {color: #F00;}

All my LI elements under the sort class function properly when the DOM is ready.

If I create a new LI element (using mootools el.addClass(classname)) I can set the base class, but can't figure out how to add a hover class to it.

Any ideas?

Share Improve this question edited Nov 18, 2011 at 1:28 Jason Plank 2,3365 gold badges32 silver badges40 bronze badges asked May 3, 2009 at 14:09 dengeldengel 3055 silver badges8 bronze badges 1
  • The MyClass:hover does not work on new elements, seems all browsers just don't consider such pseudo-class on newly inserted DOM elements. I had to work around this problem by means of adding a new event handler for the mouseover and mouseleave events and add/remove a regular MyHover class to the element. Not ideal, but works. – dengel Commented May 6, 2009 at 19:27
Add a ment  | 

5 Answers 5

Reset to default 8

The hover pseudoclass can be defined ahead of time in the stylesheet based on the classname that you're specifying. Such as:

li.classname:hover {color:#F000;}

So it's defined the same way, via the stylesheet. You would just plan ahead, knowing that you'll be defining the class name on JS-generated LI tags with a certain class, and style for it despite the fact that the list items don't exist until you create them with JavaScript.

Hover class is added automatically when you add the non hover class. E.g. if you have

.MyClass
{
...
}

.MyClass:hover
{
...
}

just add the MyClass, and the MyClass:hover will work.

:hover is not a class, but is a pseudo-selector that will select any elements the mouse is currently hovering over. If you create an li element, and add the sort class to it, then whenever you move your mouse over the element, the li.sort:hover rule should be activated, if the browser is working correctly.

Not all browsers will accept the hover pseudo class on all elements. You should consider using javascript for this effect. jQuery for example, makes this very easy.

Not all browsers will accept the hover pseudo class on all elements. You should consider using javascript for this effect. jQuery for example, makes this very easy.

To be more specific, IE6 only picks up :hover styles on anchor (a) elements.

发布评论

评论列表(0)

  1. 暂无评论