简体   繁体   English

CSS跨度悬停不起作用

[英]CSS span hover not working

I am trying to have an image show up when the user hovers over some text in a span. 当用户将鼠标悬停在跨度中的某些文本上时,我试图显示图像。 I have gotten it to work for the user hovering over an entire div, but I just want it to trigger over the span. 我已经让它为悬停在整个div上的用户工作,但我只是想让它在整个范围内触发。 Here's the full code: 这是完整的代码:

<html>
<head>
<title>gif test</title>

<style>
#gif {
    position: absolute;
    left: 50px;
    top: 120px;
    display: none;
}
#trigger:hover #gif {
    display: block;
}

</style>
</head>

<body style="font-family:Helvetica;">
<h1>gif test</h1>
<hr noshade />

<p>Hover <span id="trigger">here</span></p>
<div id="gif"><img src="img/hey.gif" /></div>
</body>

</html>

I wanted it to be so that when the user puts their mouse over "here", the image shows, but not if the mouse is over "Hover". 我希望它是这样当用户将鼠标放在“此处”时,图像显示,但是如果鼠标悬停在“悬停”上则不显示。 Is there something special about spans that prevents hovers from working the same way? 是否有一些特殊的跨距可以防止徘徊以同样的方式工作? Or am I referencing the #gif div incorrectly? 或者我错误地引用了#gif div?

Thanks. 谢谢。

Your CSS is incorrect, #trigger;hover #gif means a child of #trigger:hover with the id gif. 您的CSS不正确,#strigger; hover #gif表示#trigger的孩子:使用id gif进行悬停。 Meaning your DOM is supposed to be: 这意味着您的DOM应该是:

<div id='trigger'>
   <div id='gif'><img src='img/hey.gif' /></div>
</div>

If you want to control the state of an element outside the hierarchy, where the controlled element is not a child or a sibling, then CSS isn't enough you need some javascript: 如果你想控制层次结构之外的元素的状态,受控元素不是子元素或兄弟元素,那么CSS是不够的,你需要一些javascript:

<html>
<head>
<title>gif test</title>

<style>

#gif {
    position: absolute;
    left: 50px;
    top: 120px;
    display: none;
}

#gif.show {
    display: block;
}

</style>
</head>

<body style="font-family:Helvetica;">
<h1>gif test</h1>
<hr noshade />

<p>Hover <span id="trigger" onmouseover="show()" onmouseout="hide()">here</span></p>
<div id="gif"><img src="img/hey.gif" /></div>
</body>

<script type="text/javascript">

showBox() {
       var gifbox = document.getElementById("gif");
       gifbox.classList.add("show");
}

hideBox() {
       var gifbox = document.getElementById("gif");
       gifbox.classList.remove("show");
}

</script>
</html>

Per j08691, I had my hierarchies wrong. 根据j08691,我的层次结构错了。 New code: 新代码:

<html>
<head>
<title>gif test</title>

<style>
#gif {
    position: absolute;
    left: 50px;
    top: 120px;
    display: none;
}
#trigger:hover + #gif {
    display: block;
}

</style>
</head>

<body style="font-family:Helvetica;">
<h1>gif test</h1>
<hr noshade />

<p>Hover <span id="trigger">here</span>
<span id="gif"><img src="img/hey.gif" /></span>
</p>

</body>
</html>

Now, the image is a sibling of #trigger (both have parent <p> ; the + is the sibling selector). 现在,图像是#trigger的兄弟(两者都有父<p> ; +是兄弟选择器)。

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

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