首页 > 解决方案 > 从 SVG 创建下拉列表的疑难解答:使用悬停显示菜单

问题描述

尝试使用 CSS 中的 .class:hover > .otherClass 属性将 otherClass 的不透明度从 0 更改为 1。

在这个例子中,.class 是我粗略编辑的自行车 SVG(svg 路径代码是一个意大利面条怪物,我很抱歉——不抱歉,因为它有效)。.otherClass 是链接到 div 的属性,用于显示 ul 中的三个下一个 li。(不要真正关心他们现在的看法,只想在 css 中正确定位该组)。

这个想法是,当我将鼠标悬停在自行车 SVG 上时,下拉菜单将被显示——粗略。下面的代码:

在过去的两个小时里,我尝试了针对嵌套 .otherClass 的不同方法,但均无济于事。

HTML:

<div ="nav">

<svg class = "bike" viewBox="0 0 625 355" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/"
        style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5;">
        <g id="Bike"><path d="M108.706,153.568c51.739,0.588 93.266,43.071 92.678,94.81c-0.589,51.739 -43.072,93.266 -94.811,92.677c-51.738,-0.588 -93.266,-43.071 -92.677,-94.81c0.588,-51.739 43.071,-93.266 94.81,-92.677Z"
        style="fill:none;stroke:#000;stroke-width:12.5px;"/><path d="M107.758,236.896c5.749,0.065 10.363,4.785 10.298,10.534c-0.066,5.749 -4.786,10.363 -10.535,10.298c-5.748,-0.066 -10.363,-4.786 -10.297,-10.535c0.065,-5.749 4.785,-10.363 10.534,-10.297Z"/>
        <path d="M517.132,147.796c51.738,0.589 93.266,43.072 92.677,94.81c-0.588,51.739 -43.072,93.267 -94.81,92.678c-51.739,-0.588 -93.266,-43.072 -92.678,-94.81c0.589,-51.739 43.072,-93.266 94.811,-92.678Z"
        style="fill:none;stroke:#000;stroke-width:12.5px;"/><path d="M516.184,231.124c5.748,0.066 10.363,4.786 10.297,10.535c-0.065,5.748 -4.786,10.363 -10.534,10.297c-5.749,-0.065 -10.363,-4.786 -10.298,-10.534c0.066,-5.749 4.786,-10.363 10.535,-10.298Z"/>
        <path d="this path is absolutely massive, not including it"/>
  </g>

  <div class="drop">
  <ul>
    <li>
      <ul class="dropdown">
        <li><a href="#">Sub-1</a></li>
        <li><a href="#">Sub-2</a></li>
        <li><a href="#">Sub-3</a></li>
      </ul>
    </li>
  </ul>
  </div>

</svg>

</div>

CSS:

.bike {
  top: 5%;
  left: 5%;
  z-index: 5;
  float: center;
  width: 15%;
  position: absolute;
}

.bike:hover, .bike:hover > .drop {
  fill: blue;
  opacity:1;
}


.drop {
  opacity:0;
}

ul{
  color: green;
  width: 100px;
  height: 100px;
}

li{
  color: blue;
  width: 100px;
  height: 50px;
}

当您将鼠标悬停在 SVG 上时,下拉平均值应将其不透明度从 0 更改为 1。

标签: htmlcss

解决方案


部分问题在于您的 SVG 格式不正确。如果不将其标记为外来对象,就不能在 SVG 中包含 HTML 代码……这是因为 SVGXML Namespace就像 HTML 一样。(命名的 XML 节点以特定方式解释)。

这是. _SVG foreignObject

但是,我会通过简单地将 .drop div 移到 SVG 标记之外来避免这种情况。然后使用“下一个兄弟”选择器而不是“直接孩子”。

.bike:hover {
  fill: blue;
}
.bike:hover + .drop {
  background-color: blue;
  opacity:1;
}

在 HTML 实体上也fill:color无效,请background-color改用。这可能会导致您的浏览器在出现错误后忽略 CSS。


推荐阅读