内联样式充当:悬停在CSS中

ral*_*ldi 83 html css

我知道将CSS样式直接嵌入到它们所影响的HTML标记中会破坏CSS的大部分用途,但有时它对调试很有用,如:

<p style="font-size: 24px">asdf</p>
Run Code Online (Sandbox Code Playgroud)

嵌入规则的语法是什么:

a:hover {text-decoration: underline;}
Run Code Online (Sandbox Code Playgroud)

进入A标签的style属性?显然不是这个......

<a href="foo" style="text-decoration: underline">bar</a>
Run Code Online (Sandbox Code Playgroud)

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

Gle*_*ven 87

我担心它无法完成,伪类选择器无法在线设置,你必须在页面或样式表上进行.

我应该提到技术上应该能够根据CSS规范来做,但大多数浏览器都不支持它

编辑:我刚刚做了一个快速测试:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>
Run Code Online (Sandbox Code Playgroud)

它在IE7,IE8 beta 2,Firefox或Chrome中不起作用.其他人可以在任何其他浏览器中测试吗?

  • 很久以前发布了这个答案,事情发生了变化,以及相关W3C规范的当前版本 - CSS Style Attribute Rec.(http://www.w3.org/TR/css-style-attr/#syntax) - 清楚地说,style属性只能包含CSS声明块的内容.所以现在不可能插入带有`style`属性的伪元素. (28认同)
  • 这是一个非常低优先级的CSS 3工作草案,六年来一直没有更新.根据规范:'使用W3C工作草案作为参考资料或引用它们不是"正在进行的工作"是不合适的." (3认同)

Ale*_*aho 21

如果您只是调试,可以使用javascript来修改css:

<a onmouseover="this.style.textDecoration='underline';" 
    onmouseout="this.style.textDecoration='none';">bar</a>
Run Code Online (Sandbox Code Playgroud)


Rod*_*man 16

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

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

<a href="http://example.com" class="foo bar hovertest">blah</a>
Run Code Online (Sandbox Code Playgroud)

  • 这可能是你最接近想要的效果 (2认同)

小智 12

简单的解决方案:

   <a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>
Run Code Online (Sandbox Code Playgroud)

要么

<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>
Run Code Online (Sandbox Code Playgroud)