我有一个情况下,我必须写内联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变量内联定义styles的值:

:{徘徊 颜色:var(——hover-color); } <a style="——hover-color: green"> 图书馆 < / >

考虑在选择器之外使用属性或类(例如,[hover-color]:hover)来允许与其他低特异性悬停颜色更改规则共存(例如,CSS重置或某些元素使用默认样式)。

你可以像这样使用内联样式表语句:

<style>#T1:hover{color:red}</style><span id=T1>Your Text Here</span>

你不能完全按照你描述的去做,因为a:hover是选择器的一部分,而不是CSS规则。样式表有两个组件:

selector {rules}

内联样式只有规则;选择器隐式为当前元素。

选择器是一种表达性语言,它描述了一组匹配类xml文档中的元素的标准。

然而,你可以接近,因为从技术上讲,一个风格集几乎可以去任何地方:

<html>
  <style>
    #uniqueid:hover {do:something;}
  </style>
  <a id="uniqueid">hello</a>
</html>

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

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

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

下面是最好的代码示例:

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