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

html - How can I set a css ":hover" on a DOM created element in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I'm using the DOM to manage a JSON response from an AJAX function I'm running. The script I'm writing needs to be completely portable, so I am defining the styles for the created elements on the fly (meaning, no linking to an external CSS, and no providing CSS in the HTML doc itself, because I won't have control of the doc).

I'd like to create a hover effect on some of the elements.

example:

 #myDiv:hover { background:#000000; }

Is there a way to define that in the DOM? Or do I have to use mouseover?

I'm using the DOM to manage a JSON response from an AJAX function I'm running. The script I'm writing needs to be completely portable, so I am defining the styles for the created elements on the fly (meaning, no linking to an external CSS, and no providing CSS in the HTML doc itself, because I won't have control of the doc).

I'd like to create a hover effect on some of the elements.

example:

 #myDiv:hover { background:#000000; }

Is there a way to define that in the DOM? Or do I have to use mouseover?

Share Improve this question edited May 11, 2009 at 20:40 GEOCHET 21.3k15 gold badges77 silver badges99 bronze badges asked Apr 3, 2009 at 16:20 johnnietheblackjohnnietheblack 13.3k28 gold badges99 silver badges135 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

You can dynamically create and manipulate stylesheets. See here for some of the cross-browser issues with this approach.

I've got a wrapper function lying around which works around some of them; using it, the code would read

document.createStyleSheet().addRule('#myDiv:hover', 'background:#000000;');

you may create element with predefined class:

.h:hover{color: #c00}

var elem = document.createElement('div');
elem.className = 'h'
发布评论

评论列表(0)

  1. 暂无评论