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

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

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


当前回答

使用JavaScript:

a)增加内联样式

document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');

B)或者更难一点的方法——添加“鼠标悬停”

document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };

注意:JavaScript中的多词样式(即font-size)是一起编写的:

element.style.fontSize="12px"

其他回答

在当前的CSS迭代中不支持内联伪类声明(不过,据我所知,在未来的版本中可能会支持)。

现在,你最好的办法可能是直接在你想要样式的链接上方定义一个样式块:

<style type="text/css">
    .myLinkClass:hover {text-decoration:underline;}
</style>
<a href="/foo" class="myLinkClass">Foo!</a>

虽然“你不应该”的上下文可能适用,但可能在某些情况下你仍然想实现这一点。我的用例是根据一些数据值动态设置悬停颜色,以实现只有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>

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

下面是最好的代码示例:

<一个 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 ' }

如果您确实需要内联代码,则可以这样做。我需要它的一些悬停按钮,方法是这样的:

.hover-item { background - color: # FFF; } .hover-item:{徘徊 background - color:继承; } <a style="background-color: red;"> < div class = " hover-item”> 内容 < / div > < /

在本例中,内联代码:"background-color: red;"是悬停时的开关颜色。用你需要的颜色,然后这个解决方案。我意识到,就兼容性而言,这可能不是完美的解决方案,但如果绝对需要,这是可行的。

你可以通过在onMouseOver和onMouseOut参数中使用JavaScript更改样式来获得相同的效果,尽管如果你需要更改多个元素,这是非常低效的:

<a href=“abc.html” onMouseOver=“this.style.color='#0F0'” onMouseOut=“this.style.color='#00F'” >Text</a>

另外,我不太确定这在这里是否适用。你可能需要用document.getElementById('idForLink')来切换它。