简体   繁体   English

如何在内联 CSS 中写入“a:hover”?

[英]How can I write 'a:hover' in inline CSS?

I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.我有一个情况,我必须编写内联 CSS 代码,我想在锚点上应用 hover 样式。

How can I use a:hover in inline CSS inside the HTML style attribute?如何在 HTML 样式属性内联 CSS 中使用a:hover

Eg, you can't reliably use CSS classes in HTML emails.例如,您无法在 HTML 封电子邮件中可靠地使用 CSS 类。

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.给它一个 class 名称或 id 并使用样式表来应用样式。

:hover is a pseudo-selector and, for CSS , only has meaning within the style sheet. :hover是一个伪选择器,对于CSS ,仅在样式表中有意义。 There isn't any inline-style equivalent (as it isn't defining the selection criteria).没有任何等效的内联样式(因为它没有定义选择标准)。

Response to the OP's comments:回复 OP 的评论:

See Totally Pwn CSS with Javascript for a good script on adding CSS rules dynamically.有关动态添加 CSS 规则的好脚本,请参阅Totally Pwn CSS 和 Javascript 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.注意:以上假设有一个头部

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:您可以通过在onMouseOveronMouseOut参数中将 styles 更改为 JavaScript 来获得相同的效果,但如果您需要更改多个元素,则效率极低:

 <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.另外,我不确定this是否适用于这种情况。 You may have to switch it with document.getElementById('idForLink') .您可能必须使用document.getElementById('idForLink')进行切换。

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.但是现在(根据同一标准的最新版本,即候选推荐)你不能。

You can't do exactly what you're describing, since a:hover is part of the selector, not the CSS rules.您不能完全按照您的描述进行操作,因为a:hover是选择器的一部分,而不是 CSS 规则的一部分。 A stylesheet has two components:样式表有两个组件:

selector {rules}

Inline styles only have rules;内联styles只有规则; 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.选择器是一种表达性语言,它描述了一组标准以匹配类似 XML 的文档中的元素。

However, you can get close, because a style set can technically go almost anywhere:但是,您可以接近,因为从技术上讲, style集几乎可以在任何地方使用 go:

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

I'm extremely late contributing to this, however I was sad to see no one suggested this, if you actually require inline code, this is possible to do.我对此做出贡献的时间非常晚,但是我很遗憾没有人建议这样做,如果您确实需要内联代码,则可以这样做。 I needed it for some hover buttons, the method is this:我需要一些 hover 按钮,方法是这样的:

 .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;"在这种情况下,内联代码:“background-color: red;” is the switch colour on hover, put the colour you need into there and then this solution works.是hover上的开关颜色,把你需要的颜色放在那里,然后这个解决方案就起作用了。 I realise this may not be the perfect solution in terms of compatibility however this works if it is absolutely needed.我意识到这在兼容性方面可能不是完美的解决方案,但是如果绝对需要,它可以工作。

using Javascript:使用 Javascript:

a) Adding inline style a) 添加内联样式

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

b) or a bit harder method - adding "mouseover" 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',''); };

Note: multi-word styles (ie font-size ) in Javascript are written together :注:Javascript中的多字styles(即font-size )写在一起

element.style.fontSize="12px"

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 HTML

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

JS 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' }

While it appears to be impossible to define a hover-rule inline, you can define the value of styles inline using a CSS Variable:虽然似乎不可能内联定义悬停规则,但您可以使用 CSS 变量内联定义 styles 的

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

Consider using an attribute or a class in addition to the selector (eg [hover-color]:hover ) to allow coexistence with other low specificity hover color changing rules.除了选择器(例如[hover-color]:hover )之外,考虑使用属性或 class 以允许与其他低特异性 hover 变色规则共存。 (from eg a css reset or some elements using the default style) (例如 ZC7A62​​8CBA22E28EB17B5F5C6AE2A266AZ 重置或使用默认样式的某些元素)

Inline pseudoclass declarations aren't supported in the current iteration of CSS (though, from what I understand, it may come in a future version). CSS 的当前迭代不支持内联伪类声明(不过,据我了解,它可能会出现在未来的版本中)。

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>

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: 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;"
<style>a:hover { }</style>
<a href="/">Go Home</a>

Hover is a pseudo class, and thus cannot be applied with a style attribute. Hover 是伪 class,因此不能与样式属性一起应用。 It is part of the selector.它是选择器的一部分。

You can do this.你可以这样做。 But not in inline styles.但不在内联 styles 中。 You can use onmouseover and onmouseout events:您可以使用onmouseoveronmouseout事件:

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

There is no way to do this.没有办法做到这一点。 Your options are to use a JavaScript or a CSS block.您的选择是使用 JavaScript 或 CSS 块。

Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block.也许有一些 JavaScript 库会将专有样式属性转换为样式块。 But then the code will not be standard-compliant.但是代码将不符合标准。

According to your comments, you're sending a JavaScript file anyway.根据您的评论,无论如何您都在发送 JavaScript 文件。 Do the rollover in JavaScript.在 JavaScript 中进行翻转。 jQuery 's $.hover() method makes it easy, as does every other JavaScript wrapper. jQuery$.hover()方法使它变得容易,就像所有其他 JavaScript 包装器一样。 It's not too hard in straight JavaScript either.直接 JavaScript 也不太难。

you can write a code in various type您可以编写各种类型的代码

first i can write this首先我可以写这个

html html

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

css ZC7A62​​8CBA22E28EB17B5F5C6AE2A266AZ

.one{
  text-decoration: none;
}

you can try another way你可以尝试另一种方式

html html

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

css ZC7A62​​8CBA22E28EB17B5F5C6AE2A266AZ

.one{
text-decoration: none;
}

.one:hover{
color:blue;
}

.one:active{
color: red;
}

you can also try hover in jquery您也可以在 jquery 中尝试 hover

java script java 脚本

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

html html

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

in this code you have a three function in jquery first you ready a function which is the basic of function of jquery then second you have a hover function in this function when you hover a pointer to the text the color will be changed and then the next the when you release the pointer to the text it will be the different color and this is the third function in this code you have a three function in jquery first you ready a function which is the basic of function of jquery then second you have a hover function in this function when you hover a pointer to the text the color will be changed and then the next当您释放指向文本的指针时,它将是不同的颜色,这是第三个 function

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.我的问题:我在一些幻灯片/主要内容查看器周围有一个<a>标签,在页脚中有一个<a>标签。 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.我希望他们将 go 放到 IE 中的同一个位置,所以整个段落都会在onHover下加下划线,即使它们不是链接:整个幻灯片是一个链接。 IE doesn't know the difference. IE 不知道区别。 I also have some actual links in my footer that do need the underline and color change onHover .我的页脚中也有一些实际链接,它们确实需要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.我以为我必须将 styles 与页脚标签内联以使颜色发生变化,但上面的建议表明这是不可能的。

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我能够在一个 class 中更改onHover颜色,让幻灯片onHover没有颜色更改/下划线,并且仍然能够同时在页脚和幻灯片中使用外部 HREFS

I agree with shadow .我同意影子 You could use the onmouseover and onmouseout event to change the CSS via JavaScript.您可以使用onmouseoveronmouseout事件通过 JavaScript 更改CSS

And don't say people need to have JavaScript activated.不要说人们需要激活 JavaScript。 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.这只是一个风格问题,所以如果有一些访问者没有 JavaScript;) 虽然Web 2.0的大部分都适用于 Z686155AF75A60A0F6E9D80C1F7EDD3EZ9。 See Facebook for example (lots of JavaScript) or Myspace .例如,请参阅Facebook (大量 JavaScript)或Myspace

This is pretty late in the game, but when would you use JavaScript in an HTML Email?这在游戏中已经很晚了,但是您何时会在 HTML Email 中使用 JavaScript? For example, at the company I currently work for (rhymes with Abodee), we use the lowest common denominator for most email marketing campaigns – and JavaScript is just not being used.例如,在我目前工作的公司(与 Abodee 押韵),我们在大多数 email 营销活动中使用最低公分母——而 JavaScript 只是没有被使用。 Ever.曾经。 Unless you are referring to some kind of pre-processing.除非您指的是某种预处理。

As mentioned in a related post: "Lotus Notes, Mozilla Thunderbird, Outlook Express, and Windows Live Mail all seem to support some sort of JavaScript execution. Nothing else does."如相关帖子中所述:“Lotus Notes、Mozilla Thunderbird、Outlook Express 和 Windows Live Mail 似乎都支持某种 JavaScript 执行。”

Link to the article from which this was taken: [ http://en.wikipedia.org/wiki/Comparison_of_e-mail_clients]链接到该文章的来源:[ http://en.wikipedia.org/wiki/Comparison_of_e-mail_clients]

Also, how would hovering translate to mobile devices?此外,悬停如何转化为移动设备? That's why I like the answer from above: Long answer: you shouldn't.这就是为什么我喜欢上面的答案: Long answer: you shouldn't.

If anyone has more insights into this subject, please feel free to correct me.如果有人对此主题有更多见解,请随时纠正我。 Thank you.谢谢你。

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.我定义了一些 colors 并将它们传递给每个元素的车把模板。 At the top of the template I defined a style tag, and put in my custom class and hover color.在模板的顶部,我定义了一个样式标签,并输入了我的自定义 class 和 hover 颜色。

<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你可能不需要important

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.我的用例是根据某些数据值动态设置 hover 颜色,以仅使用 CSS 即可从特异性中受益。

Approach CSS only仅接近 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;
}

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)我正在使用车把做这个例子,但想法是你可以用任何方便的方式来设置内联样式(即使它是在 hover 上手动编写你想要的颜色)

not exactly inline CSS but it is inline lol不完全是内联 CSS 但它是内联哈哈

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

You can just use an inline stylesheet statement like this:您可以像这样使用内联样式表语句:

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

I had to avoid javascript, but could go with server side code.我不得不避免使用 javascript,但可以使用服务器端代码。

so I generated an id, created a style block, generated the link with that id.所以我生成了一个 id,创建了一个样式块,生成了具有该 id 的链接。 Yes its valid HTML.是的,它的有效 HTML。

 a { text-decoration: none; color: blue; } a:hover { color: blue; font-weight: bold; }
 <!-- some code in the interpreter you use, to generate the data-hover id --> <style> a[data-hover="rnd-id-123"] { color: green; } a[data-hover="rnd-id-123"]:hover { color: red; } </style> <a data-hover="rnd-id-123">some link 1</a> <br> <!-- some code in the interpreter you use, to generate the data-hover id --> <style> a[data-hover="rnd-id-456"] { color: purple; } a[data-hover="rnd-id-456"]:hover { color: orange; } </style> <a data-hover="rnd-id-456">some link 2</a>

It's now possible with Hacss .现在可以使用Hacss

You can use the pseudo-class a:hover in external style sheets only.您只能在外部样式表中使用伪类a:hover Therefore I recommend using an external style sheet.因此我推荐使用外部样式表。 The code is:代码是:

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

You can do id by adding a class but never inline.您可以通过添加 class 来执行 id,但不要内联。

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

2 lines but you can re-use the class everywhere. 2 行,但您可以在任何地方重复使用 class。

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 (eg blue-ish images turn red-ish on hover).我的问题是我正在构建一个网站,该网站使用大量图像图标,这些图像图标必须由 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).悬停容器时,第一个变为隐藏(显示:无),第二个再次显示(显示:块)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM