如何设置css“:hover”在JavaScript中创建DOM元素? [英] How can I set a css ":hover" on a DOM created element in JavaScript?

查看:398
本文介绍了如何设置css“:hover”在JavaScript中创建DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用DOM来管理来自我正在运行的AJAX函数的JSON响应。我写的脚本需要是完全可移植的,所以我定义的所创建的元素的样式(即,没有链接到外部CSS,并没有提供CSS在HTML文档本身,因为我不会



我想为某些元素创建悬停效果。



example:

 #myDiv:hover {background:#000000; } 

有没有办法在DOM中定义?或者我必须使用 mouseover

解决方案

并操作样式表。有关此方法的一些跨浏览器问题,请参阅此处。 p>

我有一个包装函数围绕,围绕其中一些工作;使用它,代码将读取

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


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;');

这篇关于如何设置css“:hover”在JavaScript中创建DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆