内联样式在CSS中充当:hover


90

我知道将CSS样式直接嵌入到它们会影响的HTML标记中会破坏CSS的许多目的,但是有时对于调试目的很有用,例如:

<p style="font-size: 24px">asdf</p>

嵌入规则的语法是什么:

a:hover {text-decoration: underline;}

放入A标签的样式属性中?显然不是这个...

<a href="foo" style="text-decoration: underline">bar</a>

...因为这将一直适用,而不是仅在悬停期间适用。


从理论上讲,如果要使悬停变得动态,可以使用javascript通过现有工作表的window.document.styleSheets列表将悬停规则注入样式表中。
GAgnew

Answers:


95

恐怕无法完成,伪类选择器无法内联设置,您必须在页面或样式表上进行设置。

我应该提到,从技术上讲,应该能够按照CSS规范进行操作,但是大多数浏览器均不支持

编辑:我只是对此进行了快速测试:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>

而且它不适用于IE7,IE8 beta 2,Firefox或Chrome。其他人可以在其他任何浏览器中进行测试吗?


3
这是一个非常低优先级的CSS 3工作草案,六年来一直没有更新。从规范来看:“将W3C工作草案用作参考资料或将其引用为“正在进行的工作”是不合适的。'
吉姆

1
没错,但是浏览器确实实现了一些CSS3规则,在这种情况下应该是错误的词
Glenn Slaven

浏览器通常会实现处于进一步开发状态的CSS功能,例如,不透明来自CSS颜色(最后一次调用),而媒体查询是候选推荐。
吉姆(Jim)

style =“:hover {}”等同于样式表中的“ a {:hover {}}”吗?那显然是语法错误。
Kornel

32
这个答案发布很久以前,从那以后,事情发生了变化,相关的W3C规范的当前版本为CSS样式属性记录。(w3.org/TR/css-style-attr/#syntax)—明确指出style属性只能包含CSS声明块的内容。因此,现在无法插入带有style属性的伪元素。
Ilya Streltsyn 2014年

24

如果仅调试,则可以使用javascript修改css:

<a onmouseover="this.style.textDecoration='underline';" 
    onmouseout="this.style.textDecoration='none';">bar</a>

1
使用JSF搜索了一个解决方案,这有助于我对其进行修复。onmousemove =“ this.style.color ='## {cc.attrs.color}';” onmouseout =“ this.style.color ='white';”
kdoteu 2014年

16

如果是用于调试,则只需添加一个css类进行悬停(因为元素可以具有多个类):

a.hovertest:hover
{
text-decoration:underline;
}

<a href="http://example.com" class="foo bar hovertest">blah</a>

2
这可能是最接近所需效果的位置
Glenn Slaven

16

一个简单的解决方案:

   <a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>

要么

<script>
 /** Change the style **/
 function overStyle(object){
    object.style.color = 'orange';
    // Change some other properties ...
 }

 /** Restores the style **/
 function outStyle(object){
    object.style.color = 'orange';
    // Restore the rest ...
 }
</script>

<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>

1

我为想要使用onmouseover和onmouseout行为而不使用CSS创建悬停弹出窗口的任何人提供了一个快速解决方案。

http://jsfiddle.net/Lk9w1mkv/

<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>


-2

我也不认为jQuery也支持伪选择器,但它确实提供了一种将事件添加到单个页面上的一个,多个或所有相似控件和标记的快速方法。

最重要的是,您可以链接事件绑定,并根据需要在一行脚本中完成所有操作。与手动编辑所有HTML以将其打开或关闭相比,要容易得多。再说一次,由于您可以在CSS中进行相同的操作,因此我不知道它可以为您带来任何收益(除了学习jQuery外)。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.