我有一个情况下,我必须写内联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>

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

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

selector {rules}

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

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

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

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

只能在外部样式表中使用伪类a:hover。因此,我建议使用外部样式表。代码是:

a:hover {color:#FF00FF;}   /* Mouse-over link */

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

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

您可以编写各种类型的代码。

首先我可以这样写

HTML

<a href="https://www.google.com/" onMouseOver="this.style.color='red'"
        onMouseOut="this.style.color='blue'" class="one">Hello siraj</a>

CSS

.one {
    text-decoration: none;
}

你可以试试另一种方法:

HTML

<a href="https://www.google.com/" class="one">Hello siraj</a>

CSS

.one {
    text-decoration: none;
}

.one:hover {
    color: blue;
}

.one:active {
    color: red;
}

你也可以在jQuery中尝试hover:

JavaScript

$(document).ready(function() {
  $("p").hover(function() {
    $(this).css("background-color", "yellow");
    }, function() {
      $(this).css("background-color", "pink");
  });
});

HTML

<p>Hover the mouse pointer over this paragraph.</p>

在这段代码中,有三个jQuery函数。首先你准备一个函数,这是jQuery的基本函数。其次,在这个函数中有一个悬停函数。当你将一个指针悬停到文本上时,颜色会改变,然后当你释放指向文本的指针时,它会是不同的颜色,这是第三个函数。