我怎样才能写“a:hover” 在内联CSS中?

发布于 2024-07-25 04:45:30 字数 142 浏览 11 评论 0原文

我有一个情况,我必须编写内联 CSS 代码,并且我想在锚点上应用悬停样式。

如何在 HTML 样式属性内的内联 CSS 中使用 a:hover

例如,您无法在 HTML 电子邮件中可靠地使用 CSS 类。

I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.

How can I use a:hover in inline CSS inside the HTML style attribute?

E.g., you can't reliably use CSS classes in HTML emails.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

枫林﹌晚霞¤ 2024-08-01 04:45:30

简短的回答:你不能。

长答案:你不应该。

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

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

对OP评论的回应:

参见完全Pwn CSS with Javascript 是一个动态添加 CSS 规则的好脚本。 另请参阅更改样式表了解有关主题。

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

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

警告:上面假设有一个 head 部分。

Short answer: you can't.

Long answer: you shouldn't.

Give it a class name or an id and use stylesheets to apply the style.

:hover is a pseudo-selector and, for CSS, only has meaning within the style sheet. There isn't any inline-style equivalent (as it isn't defining the selection criteria).

Response to the OP's comments:

See Totally Pwn CSS with Javascript for a good script on adding CSS rules dynamically. Also see Change style sheet for some of the theory on the subject.

Also, don't forget, you can add links to external stylesheets if that's an option. For example,

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

Caution: the above assumes there is a head section.

三寸金莲 2024-08-01 04:45:30

您可以通过在 onMouseOveronMouseOut 参数中使用 JavaScript 更改样式来获得相同的效果,但如果您需要更改多个元素,则效率极低:

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

另外,我无法确定 this 在这种情况下是否有效。 您可能需要使用 document.getElementById('idForLink') 进行切换。

You can get the same effect by changing your styles with JavaScript in the onMouseOver and onMouseOut parameters, although it's extremely inefficient if you need to change more than one element:

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

Also, I can't remember for sure if this works in this context. You may have to switch it with document.getElementById('idForLink').

空心↖ 2024-08-01 04:45:30

您可以在过去的某个时刻做到。 但现在(根据同一标准的最新修订版,即候选推荐)你不能

You could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't
.

盗梦空间 2024-08-01 04:45:30

虽然似乎不可能内联定义悬停规则,但您可以使用 CSS 变量定义内联样式的

:hover {
  color: var(--hover-color);
}
<a style="--hover-color: green">
    Library
</a>

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

While it appears to be impossible to define a hover-rule inline, you can define the value of styles inline using a CSS variable:

:hover {
  color: var(--hover-color);
}
<a style="--hover-color: green">
    Library
</a>

Consider using an attribute or a class in addition to the selector (e.g., [hover-color]:hover) to allow coexistence with other low specificity hover color changing rules (from, e.g., a CSS reset or some elements using the default style).

自由范儿 2024-08-01 04:45:30

您无法完全按照您所描述的操作,因为 a:hover 是选择器的一部分,而不是 CSS 规则的一部分。 样式表有两个组成部分:

selector {rules}

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

选择器是一种表达性语言,它描述了一组用于匹配类似 XML 文档中的元素的条件。

但是,您可以接近,因为 style 集从技术上讲几乎可以放在任何地方:

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

You can't do exactly what you're describing, since a:hover is part of the selector, not the CSS rules. A stylesheet has two components:

selector {rules}

Inline styles only have rules; the selector is implicit to be the current element.

The selector is an expressive language that describes a set of criteria to match elements in an XML-like document.

However, you can get close, because a style set can technically go almost anywhere:

<html>
  <style>
    #uniqueid:hover {do:something;}
  </style>
  <a id="uniqueid">hello</a>
</html>
各自安好 2024-08-01 04:45:30

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

.hover-item {
    background-color: #FFF;
}

.hover-item:hover {
    background-color: inherit;
}
<a style="background-color: red;">
    <div class="hover-item">
        Content
    </div>
</a

在本例中,内联代码:“background-color: red;” 是悬停时的开关颜色。 使用您需要的颜色,然后该解决方案就可以工作。 我意识到这可能不是兼容性方面的完美解决方案,但是如果绝对需要的话,这是可行的。

If you actually require inline code, this is possible to do. I needed it for some hover buttons, and the method is this:

.hover-item {
    background-color: #FFF;
}

.hover-item:hover {
    background-color: inherit;
}
<a style="background-color: red;">
    <div class="hover-item">
        Content
    </div>
</a

In this case, the inline code: "background-color: red;" is the switch colour on hover. Use the colour you need and then this solution works. I realise this may not be the perfect solution in terms of compatibility, however this works if it is absolutely needed.

迷爱 2024-08-01 04:45:30

使用 JavaScript:

a) 添加内联样式

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

b) 或更难一点的方法 - 添加“mouseover”

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"

Using JavaScript:

a) Adding inline style

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

b) or a bit harder method - adding "mouseover"

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',''); };

Note: multi-word styles (i.e.font-size) in JavaScript are written together:

element.style.fontSize="12px"
十二 2024-08-01 04:45:30

这是最好的代码示例:

<a
 style="color:blue;text-decoration: underline;background: white;"
 href="http://aashwin.com/index.php/education/library/"
 onmouseover="this.style.color='#0F0'"
 onmouseout="this.style.color='#00F'">
   Library
</a>

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

超文本标记语言

<a
 style="color:blue;text-decoration: underline;background: white;"
 href="http://aashwin.com/index.php/education/library/"
 class="lib-link">
   Library
</a>

JS

const libLink = document.getElementsByClassName("lib-link")[0];
// The array 0 assumes there is only one of these links,
// you would have to loop or use event delegation for multiples
// but we won't go into that here
libLink.onmouseover = function () {
  this.style.color='#0F0'
}
libLink.onmouseout = function () {
  this.style.color='#00F'
}

This is the best code example:

<a
 style="color:blue;text-decoration: underline;background: white;"
 href="http://aashwin.com/index.php/education/library/"
 onmouseover="this.style.color='#0F0'"
 onmouseout="this.style.color='#00F'">
   Library
</a>

Moderator Suggestion: Keep your separation of concerns.

HTML

<a
 style="color:blue;text-decoration: underline;background: white;"
 href="http://aashwin.com/index.php/education/library/"
 class="lib-link">
   Library
</a>

JS

const libLink = document.getElementsByClassName("lib-link")[0];
// The array 0 assumes there is only one of these links,
// you would have to loop or use event delegation for multiples
// but we won't go into that here
libLink.onmouseover = function () {
  this.style.color='#0F0'
}
libLink.onmouseout = function () {
  this.style.color='#00F'
}

旧伤还要旧人安 2024-08-01 04:45:30

正如所指出的,您不能为悬停设置任意内联样式,但您可以在适当的标记中使用以下内容更改 CSS 中悬停光标的样式:

style="cursor: pointer;"

As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:

style="cursor: pointer;"
唠甜嗑 2024-08-01 04:45:30

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

目前,您最好的选择可能是在您想要设置样式的链接正上方定义一个样式块:

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

Inline pseudoclass declarations aren't supported in the current iteration of CSS (though, from what I understand, it may come in a future version).

For now, your best bet is probably to just define a style block directly above the link you want to style:

<style type="text/css">
    .myLinkClass:hover {text-decoration:underline;}
</style>
<a href="/foo" class="myLinkClass">Foo!</a>
流年已逝 2024-08-01 04:45:30

你可以这样做。 但在内联样式中则不然。 您可以使用 onmouseoveronmouseout 事件:

<div style="background: #333; padding: 10px; cursor: pointer"
   onmouseover="this.style.backgroundColor='#555';" onmouseout="this.style.backgroundColor='#333';">
      Hover on me!
</div>

You can do this. But not in inline styles. You can use onmouseover and onmouseout events:

<div style="background: #333; padding: 10px; cursor: pointer"
   onmouseover="this.style.backgroundColor='#555';" onmouseout="this.style.backgroundColor='#333';">
      Hover on me!
</div>

一口甜 2024-08-01 04:45:30
<style>a:hover { }</style>
<a href="/">Go Home</a>

Hover 是一个伪类,因此不能与样式属性一起应用。 它是选择器的一部分。

<style>a:hover { }</style>
<a href="/">Go Home</a>

Hover is a pseudo class, and thus cannot be applied with a style attribute. It is part of the selector.

奢华的一滴泪 2024-08-01 04:45:30

它不完全是内联 CSS,但它是内联的。

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

It's not exactly inline CSS, but it is inline.

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

吃颗糖壮壮胆 2024-08-01 04:45:30

根据您的评论,您无论如何都会发送 JavaScript 文件。 在 JavaScript 中进行翻转。 jQuery$.hover() 方法使它变得简单,与其他所有 JavaScript 包装器一样。 在直接的 JavaScript 中这也不是太难。

According to your comments, you're sending a JavaScript file anyway. Do the rollover in JavaScript. jQuery's $.hover() method makes it easy, as does every other JavaScript wrapper. It's not too hard in straight JavaScript either.

简单气质女生网名 2024-08-01 04:45:30

没有办法做到这一点。 您可以选择使用 JavaScript 或 CSS 块。

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

There is no way to do this. Your options are to use a JavaScript or a CSS block.

Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.

櫻之舞 2024-08-01 04:45:30

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

我的问题:我在一些幻灯片/主要内容查看器周围有一个 标签,以及页脚中的 标签。 我希望它们在 IE 中转到同一位置,因此整个段落都会在 onHover 上加下划线,即使它们不是链接:整个幻灯片是一个链接。 IE不知道有什么区别。 我的页脚中还有一些实际链接,它们确实需要下划线和颜色更改 onHover。 我认为我必须将样式与页脚标签内联才能改变颜色,但上面的建议表明这是不可能的。

解决方案:我给页脚链接提供了两个不同的类,我的问题就解决了。 我能够在一个类中更改 onHover 颜色,让幻灯片 onHover 没有颜色更改/下划线,并且仍然能够在页脚中包含外部 HREFS,同时播放幻灯片!

I just figured out a different solution.

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.

Solution: I gave the footer links two different classes, and my problem was solved. I was able to have the onHover color change in one class, have the slides onHover have no color change/underline, and still able to have the external HREFS in the footer and the slides at the same time!

眼中杀气 2024-08-01 04:45:30

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

首先我可以写这个

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

你也可以尝试将鼠标悬停在 < a href="https://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery:

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 函数的基础。 其次,这个函数中有一个悬停函数。 当您将指针悬停在文本上时,颜色将发生变化,然后当您将指针释放到文本上时,颜色将变为不同的颜色,这是第三个功能。

You can write code in various type.

First I can write this

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

You can try another way:

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

You can also try hover in jQuery:

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>

In this code you have three functions in jQuery. First you ready a function which is the basic of a function of jQuery. Then secondly, you have a hover function in this function. When you hover a pointer to the text, the color will be changed and then next when you release the pointer to the text, it will be the different color, and this is the third function.

金橙橙 2024-08-01 04:45:30

我同意影子。 您可以使用 onmouseoveronmouseout 事件来更改 CSS 通过 JavaScript。

并且不要说人们需要激活 JavaScript。 这只是一个样式问题,所以如果有一些访问者没有 JavaScript 也没关系;)
尽管大多数 Web 2.0 都可以使用 JavaScript。 例如,请参阅 Facebook(大量 JavaScript)或 Myspace

I agree with shadow. You could use the onmouseover and onmouseout event to change the CSS via JavaScript.

And don't say people need to have JavaScript activated. It's only a style issue, so it doesn't matter if there are some visitors without JavaScript ;)
Although most of Web 2.0 works with JavaScript. See Facebook for example (lots of JavaScript) or Myspace.

心碎的声音 2024-08-01 04:45:30

所以这并不完全是用户想要的,但我发现这个问题正在寻找答案并提出了一些相关的东西。 我有一堆重复的元素,需要为其中的选项卡使用新的颜色/悬停。 我使用车把,这是我的解决方案的关键,但其他模板语言也可能有效。

我定义了一些颜色并将它们传递到每个元素的车把模板中。 在模板的顶部,我定义了一个样式标签,并放入了我的自定义类和悬停颜色。

<style type="text/css">
    .{{chart.type}}-tab-hover:hover {
        background-color: {{chart.chartPrimaryHighlight}} !important;
    }
</style>

然后我在模板中使用了样式:

<span class="financial-aid-details-header-text {{chart.type}}-tab-hover">
   Payouts
</span>

您可能不需要 !important

So this isn't quite what the user was looking for, but I found this question searching for an answer and came up with something sort of related. I had a bunch of repeating elements that needed a new color/hover for a tab within them. I use handlebars, which is key to my solution, but other templateing languages may also work.

I defined some colors and passed them into the handlebars template for each element. At the top of the template I defined a style tag, and put in my custom class and hover color.

<style type="text/css">
    .{{chart.type}}-tab-hover:hover {
        background-color: {{chart.chartPrimaryHighlight}} !important;
    }
</style>

Then I used the style in the template:

<span class="financial-aid-details-header-text {{chart.type}}-tab-hover">
   Payouts
</span>

You may not need the !important

陪你搞怪i 2024-08-01 04:45:30

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

我使用把手来做这个示例,但想法是,您可以采取任何对您的用例方便的方式来设置内联样式(即使它是在悬停时手动写入您想要的颜色)

While the "you shouldn't" context may apply there may be cases were you still want to achieve this. My use case was to dynamic set a hover color depending on some data value to achieve that with only CSS you can benefit from specificity.

Approach CSS only

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

Then your markup will be somewhat like:

Markup

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

I'm doing this example using handlebars but the idea is that you take whatever is convenient for your use case to set the inline style (even if it is writing manually the color on hover you want)

回眸一遍 2024-08-01 04:45:30

您可以只使用内联样式表语句,如下所示:

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

You can just use an inline stylesheet statement like this:

<style>#T1:hover{color:red}</style><span id=T1>Your Text Here</span>
梦回梦里 2024-08-01 04:45:30

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

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

You can use the pseudo-class a:hover in external style sheets only. Therefore I recommend using an external style sheet. The code is:

a:hover {color:#FF00FF;}   /* Mouse-over link */
烟花肆意 2024-08-01 04:45:30

您可以通过添加类来执行 id,但不能内联。

<style>.hover_pointer{cursor:pointer;}</style>
<div class="hover_pointer" style="font:bold 12pt Verdana;">Hello World</div>

它只有两行,但您可以在任何地方重用该类。

You can do id by adding a class, but never inline.

<style>.hover_pointer{cursor:pointer;}</style>
<div class="hover_pointer" style="font:bold 12pt Verdana;">Hello World</div>

It is two lines, but you can reuse the class everywhere.

无敌元气妹 2024-08-01 04:45:30

我的问题是,我正在构建一个网站,该网站使用大量图像图标,这些图标必须在悬停时被不同的图像交换(例如,蓝色图像在悬停时变成红色)。
我为此制定了以下解决方案:

.container div {
  width: 100px;
  height: 100px;
  background-size: 100px 100px;
}
.container:hover .withoutHover {
  display: none;
}
.container .withHover {
  display: none;
}
.container:hover .withHover {
  display: block;
}
<p>Hover the image to see it switch with the other. Note that I deliberately used inline CSS because I decided it was the easiest and clearest solution for my problem that uses more of these image pairs (with different URL's).
</p>
<div class=container>
<div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div>
<div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div>
</div>

我引入了一个包含这对图像的容器。 第一个是可见的,另一个是隐藏的(显示:无)。 将鼠标悬停在容器上时,第一个会隐藏 (display:none),第二个会再次显示 (display:block)。

My problem was that I'm building a website which uses a lot of image-icons that have to be swapped by a different image on hover (e.g. blue-ish images turn red-ish on hover).
I produced the following solution for this:

.container div {
  width: 100px;
  height: 100px;
  background-size: 100px 100px;
}
.container:hover .withoutHover {
  display: none;
}
.container .withHover {
  display: none;
}
.container:hover .withHover {
  display: block;
}
<p>Hover the image to see it switch with the other. Note that I deliberately used inline CSS because I decided it was the easiest and clearest solution for my problem that uses more of these image pairs (with different URL's).
</p>
<div class=container>
<div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div>
<div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div>
</div>

I introduced a container containing the pair of images. The first is visible and the other is hidden (display:none). When hovering the container, the first becomes hidden (display:none) and the second shows up again (display:block).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文