如何在 html-tag 中使用 CSS 悬停?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1834537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:27:27  来源:igfitidea点击:

How to use CSS hover inside html-tag?

htmlcss

提问by Johan

I want to do something like this:

我想做这样的事情:

<li style="hover:background-color:#006db9;">

But it wont work. Is this possible to do in some way, or do I have to write the css in the head or external css-document?

但它不会工作。这是否可以以某种方式完成,或者我是否必须在头部或外部 css 文档中编写 css?

采纳答案by Zack The Human

This is not possible using the styleattribute. You'll have to use CSS, either in the document itself or in an external file.

使用该style属性是不可能的。您必须在文档本身或外部文件中使用 CSS。

li:hover { background-color:#006db9; }

If that's not an option then you'll have to resort to JavaScript.

如果这不是一个选项,那么您将不得不求助于 JavaScript。

回答by Residuum

It is not possible with inline styles, but the (in)famous onmouseover / onmouseout event handler can do the same thing.

内联样式是不可能的,但是(in)著名的 onmouseover / onmouseout 事件处理程序可以做同样的事情。

<li onmouseover="this.style.backgroundColor='#006db9'" onmouseout="this.style.backgroundColor=''">

Caveat: CSS definitions with hyphens have to be translated to Javascript using camelCase, like (css)background-color = (javascript)backgroundColor

警告:带有连字符的 CSS 定义必须使用驼峰式大小写转换为 Javascript,例如 (css)background-color = (javascript)backgroundColor

回答by Pekka

AFAIK this can't be done inline without Javascript. You will have to put it into the head or external stylesheets as you already suggest.

AFAIK 如果没有 Javascript,这无法内联完成。您必须按照您的建议将其放入头部或外部样式表中。

A <style>tag in the body is also interpreted by all browsers I know but is not valid and therefore not recommendable.

<style>正文中的标签也被我知道的所有浏览器解释,但无效,因此不推荐。

回答by Lucas

AFAIK You can't use pseudo-classes (:hover, :active, etc) on inline css.

AFAIK 您不能在内联 css 上使用伪类(:hover、:active 等)。

回答by Isaac

Instead of just having the <li>, you can nest it in an anchors tag <a href="#" class="hoverable">and then put this styling at the top of the file or in an external CSS file:

而不是仅仅有<li>,你可以嵌套它的锚标记<a href="#" class="hoverable">,然后把这个造型在文件的顶部或外部CSS文件:

a.hoverable:hover{background-color:#006db9}

Or you can just use Javascript to avoid using the anchor tag.

或者您可以仅使用 Javascript 来避免使用锚标记。

I'd recommend JQuery.

我会推荐JQuery