【问题标题】:CSS span hover not workingCSS跨度悬停不起作用
【发布时间】:2014-05-18 01:24:46
【问题描述】:

当用户将鼠标悬停在跨度中的某些文本上时,我试图显示图像。我已经让它为悬停在整个 div 上的用户工作,但我只是希望它在跨度上触发。完整代码如下:

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

我希望这样当用户将鼠标悬停在“此处”时,图像会显示,但如果鼠标悬停在“悬停”上则不会。跨度是否有什么特别之处可以防止悬停以相同的方式工作?还是我错误地引用了#gif div?

谢谢。

【问题讨论】:

  • #trigger:hover #gif 查找 ID 为 gif 的元素,它是 #trigger 的后代,但它不是。在您的代码中,#gif#trigger 的父级的兄弟,并且 CSS 中还没有父级选择器。
  • 哦,那行得通。谢谢。我会回答我自己的问题。

标签: html css hover


【解决方案1】:

您的 CSS 不正确,#trigger;hover #gif 表示 ID 为 gif 的 #trigger:hover 的子项。这意味着您的 DOM 应该是:

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

如果你想控制层次结构之外的元素的状态,其中受控元素不是子元素或兄弟元素,那么 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>

【讨论】:

  • 同级选择器确实有效,但您更改了 DOM 以实现这一点,应该避免这种情况。
  • 那么最好的方法是什么? Javascript?
  • 是的。这是我在解决方案中所做的
【解决方案2】:

根据 j08691,我的层次结构错误。新代码:

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

现在,图像是#trigger 的同级(两者都有父级&lt;p&gt;+ 是同级选择器)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2013-04-13
    • 2014-07-22
    • 2014-12-15
    • 2012-09-03
    • 2017-08-26
    相关资源
    最近更新 更多