简体   繁体   English

如何在JavaScript中的DOM创建元素上设置css“:hover”?

[英]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.

相关问题 如何使用由JavaScript函数创建的CSS设置DOM元素的样式 - How to style DOM element with CSS that was created with JavaScript function 如何在使用JavaScript创建的SVG元素上设置viewBox? - How can I set a viewBox on an SVG element created with JavaScript? 如何将Angular Directive设置为Javascript中创建的DOM元素 - How to Set Angular Directive to the DOM element created in Javascript 如何注册其DOM元素已由另一个JavaScript库创建的Angular2组件? - How can I register an Angular2 Component whose DOM element has been created by another javascript library? 如何使用javascript设置元素的内联CSS样式? - How can I set inline css styles for an element with javascript? 如何使用 JavaScript Hover 事件更改特定元素的 CSS(BG 颜色)? - How can I change the CSS (BG Color) of a specific element with JavaScript Hover events? 如何将 jQuery Function 应用于新创建的 DOM 元素? - How can I apply a jQuery Function to a newly created DOM Element? 如何在同一函数中为最近创建的DOM元素设置动画? - How can I animate a recently created DOM element in the same function? 使用Javascript DOM的CSS悬停 - CSS hover using Javascript DOM 获取动态创建的元素(Javascript,DOM)的CSS宽度 - Getting CSS width of dynamically created element (Javascript, DOM)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM