使用 :hover javascript 设置样式
据我了解,由于浏览器兼容性,以下方法非常适合设置 CSS 样式。
element.style.cssText = "color:red;";
我不能做的是使用 cssText
在 :hover
和 :focus
CSS 事件上应用样式。
我该怎么办而不是这个?
element.style.cssText = ":focus{color:red;}";
PS 不要提及使用 javascript 事件,例如 onmouseover
而不是 CSS :hover
(它不适合我的情况。)
I understand that the following method is great for setting CSS styles because of browser compatibility.
element.style.cssText = "color:red;";
What I can't do is use cssText
to apply styles on the :hover
and :focus
CSS events.
What do I do instead of this?
element.style.cssText = ":focus{color:red;}";
P.S. Don't mention using javascript events such as onmouseover
instead of the CSS :hover
( It doesn't fit my situation.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以用一些 Voodoo 魔法来做到这一点:
不完全是你所需要的,但如果你愿意,你可以调整它并用它制作一个奇特的功能。
You can do it with some Voodoo magic:
Not exactly what you needed, but you can tweak it and make a fancy function out of it if you want.
您始终可以将单独的样式规则添加到现有样式表,而不是创建新的样式元素。大致如下:
我改编了 MDN 上的 示例
这假设您正在使用一个类(已定义并应用)来添加 :hover 伪选择器,但它也可以很容易地成为 ID 或元素选择器。
如果您无法添加预先定义类或样式规则,您也可以以大致相同的方式动态执行此操作(定义类,定义类:悬停,然后将类应用于所需元素)。
You could always add an individual style rule to an existing style sheet, instead of creating a new style element. Something along the lines of:
I adapted the example at MDN
This assumes you are using a class (that is already defined and applied) to add the :hover pseudo-selector to, but it could just as easily be an ID or element selector.
If you were unable to add a class or style rule beforehand, you could also do that dynamically in much the same way (define class, define class:hover, then apply class to desired elements).