javascript 如何向跨度添加鼠标悬停效果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26545058/
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
How can I add a mouseover effect to a span?
提问by Ali Bdeir
I'm trying to do something, like when you Mouseover on text inside a span, the background changes. My code:
我正在尝试做一些事情,例如当您将鼠标悬停在跨度内的文本上时,背景会发生变化。我的代码:
<script>
function unhighlight(x) {
x.style.backgroundColor="transparent"
}
function highlight(x) {
x.style.backgroundColor="red"
}
</script>
<span onmouseover="highlight(this)" onmouseout="unhighlight(this)">
<h2>What's New</h2>
</span>
The reason I don't apply it to the h2 is a little complicated. Don't need to explain. Help?
我不将它应用于 h2 的原因有点复杂。不用解释。帮助?
回答by Alex Char
Your javacript is fine.
你的 javacript 很好。
The span element is the inline level generic container. It also helps to inform the structure of document, but it is used to group or wrap other inline elements and/or text, rather than block level elements.
span 元素是内联级别的通用容器。它还有助于告知文档的结构,但它用于分组或包装其他内联元素和/或文本,而不是块级元素。
So h2
is not valid child for span
:
所以h2
对于span
以下情况无效的孩子:
function unhighlight(x) {
x.style.backgroundColor = "transparent"
}
function highlight(x) {
x.style.backgroundColor = "red"
}
span {
display: block;
}
<span onmouseover="highlight(this);" onmouseout="unhighlight(this)"><h2>What's New</h2></span>
I suggest for containers to use block elements like div
. And also i suggest to use css for this:
我建议容器使用块元素,如div
. 而且我建议为此使用 css:
div:hover {
background: red;
}
<div>
<h2>What's New</h2>
</div>
回答by Legionar
Just set CSS to <span>
只需将 CSS 设置为 <span>
display: block;
回答by lapin
You need to change your span element to an inline block for this to work :
您需要将 span 元素更改为内联块才能使其工作:
span {
display: inline-block;
}
But note that you can achieve the same effect with CSS only :
但请注意,您只能使用 CSS 实现相同的效果:
span {
display: inline-block;
background-color: transparent;
}
span:hover {
background-color: red;
}
回答by cн?dk
You don't need javascript to do it, just with HTMLand CSS:
你不需要 javascript 来做,只需要HTML和CSS :
#myText {
display: inline-block;
background-color: transparent;
}
#myText:hover {
display: inline-block;
background-color: red;
}
<span id="myText"><h2>What's New</h2></span>