我有一个情况下,我必须写内联CSS代码,我想应用悬停样式的锚。

我如何使用一个:悬停在内联CSS内的HTML样式属性?

例如,你不能可靠地在HTML电子邮件中使用CSS类。


当前回答

你可以做到的。但不是内联样式。你可以使用onmouseover和onmouseout事件:

<div style="background: #333;填充:10 px;光标:指针” onmouseover = " this.style.backgroundColor =“# 555”;“onmouseout = " this.style.backgroundColor =“# 333”;" > 在我身上盘旋! < / div >

其他回答

简单的回答是:你不能。

长话短说:你不应该。

给它一个类名或id,并使用样式表应用样式。

:hover是一个伪选择器,对于CSS来说,它只在样式表中有意义。没有任何内联样式的对等物(因为它没有定义选择标准)。

回应行政长官的评论:

关于动态添加CSS规则的好脚本,请参阅完全Pwn CSS with Javascript。关于这个主题的一些理论,请参见Change样式表。

另外,不要忘记,如果可以的话,还可以添加到外部样式表的链接。例如,

<script type="text/javascript">
  var link = document.createElement("link");
  link.setAttribute("rel","stylesheet");
  link.setAttribute("href","http://wherever.com/yourstylesheet.css");
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(link);
</script>

注意:以上假设有一个头部部分。

虽然“你不应该”的上下文可能适用,但可能在某些情况下你仍然想实现这一点。我的用例是根据一些数据值动态设置悬停颜色,以实现只有CSS可以受益于特异性。

只使用CSS

CSS


/* Set your parent color for the inherit property */
.sidebar {
  color: green;
}

/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
  color: inherit
}

.list-item a:hover {
  color: inherit
}

/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
  color: inherit !important;
}

然后你的标记会像这样:

标记

<nav class="sidebar">
  <ul>
    <li class="list-item">
      <a
        href="/foo"
        class="dynamic-hover-color"
        style="color: #{{category.color}};"
      >
        Category
      </a>
    </li>
  </ul>
</nav>

我用把手来做这个例子,但想法是你采取任何方便你的用例来设置内联样式(即使它是手动写你想要的悬停颜色)

我只是想出了一个不同的解决方案。

My issue: I have an <a> tag around some slides/main content viewer as well as <a> tags in the footer. I want them to go to the same place in IE, so the whole paragraph would be underlined onHover, even though they're not links: the slide as a whole is a link. IE doesn't know the difference. I also have some actual links in my footer that do need the underline and color change onHover. I thought I would have to put styles inline with the footer tags to make the color change, but advice from above suggests that this is impossible.

解决方案:我给了脚注链接两个不同的类,我的问题就解决了。我能够有onHover的颜色改变在一个类,有幻灯片onHover没有颜色变化/下划线,仍然能够有外部href在页脚和幻灯片在同一时间!

这是不可能的。您可以选择使用JavaScript或CSS块。

也许有一些JavaScript库可以将私有样式属性转换为样式块。但是这样代码就不符合标准了。

下面是最好的代码示例:

<一个 Style =" font - family:宋体;font - family:宋体;" href = " http://aashwin.com/index.php/education/library/ " onmouseover = " this.style.color = # 0 f0” onmouseout = " this.style.color = # 00 f”> 图书馆 < / >

主持人建议:保持关注点的分离。

超文本标记语言 <一个 Style =" font - family:宋体;font - family:宋体;" href = " http://aashwin.com/index.php/education/library/ " 类= " lib-link " > 图书馆 < / >

JS

const libLink = document.getElementsByClassName("lib-link")[0]; //数组0假设只有一个链接, //你将不得不循环或使用事件委托为多个 //但我们不会在这里深入讨论 libLink。Onmouseover = function () { this.style.color = ' # 0 f0 ' } libLink。Onmouseout = function () { this.style.color = ' # 00 f ' }