Inline style to act as :hover in CSS

I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in:

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

What's the syntax for embedding a rule like:

a:hover {text-decoration: underline;}

into the style attribute of an A tag? It's obviously not this...

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

...since that would apply all the time, as opposed to just during hover.

378987 次浏览

恐怕不行,伪类选择器不能内联设置,您必须在页面或样式表上设置。

我应该提到的是,严格来说应该能够做到这一点 根据 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 上都不能工作。其他人可以在其他浏览器中进行测试吗?

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

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

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

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


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

一个简单的解决办法:

<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>

I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.

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>

如果这个 <p>标记是从 JavaScript 创建的,那么您还有另一个选择: 使用 JSS 以编程方式将样式表插入到文档头中。它确实支持 '&:hover'https://cssinjs.org/