[英]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. 我正在使用DOM来管理我正在运行的AJAX函数的JSON响应。 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). 我正在编写的脚本需要完全可移植,因此我正在为动态创建元素定义样式(意思是,没有链接到外部CSS,也没有在HTML文档本身提供CSS,因为我不会控制文件)。
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? 有没有办法在DOM中定义它? Or do I have to use mouseover
? 或者我必须使用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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.