简体   繁体   中英

How can I set a css “:hover” on a DOM created element in JavaScript?

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 ?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM