当悬停发生在另一个元素上时,在元素上设置css样式

时间:2017-09-01 09:36:11

标签: css svg

我在布局中有两个图像。他们的布局无法改变。当我将鼠标悬停在svg图像上时,我会更改填充颜色。如果我将鼠标悬停在第一张图片上,我还想更改svg的填充颜色。这可能吗?重要的是,悬停事件发生在第一个图像上,而不是在根div上。

https://jsfiddle.net/Deepview/3awtx16v/

<div class="outer">
  <img src="https://i.pinimg.com/originals/11/94/f3/1194f3b0cb86afdf0d610e7b0b105826.png" />
  <div>
      <svg enable-background="new 0 0 128 128" height="128px" id="Layer_1" version="1.1" viewBox="0 0 128 128" width="128px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M64,128C28.71,128,0,99.29,0,64C0,28.71,28.71,0,64,0c35.29,0,64,28.71,64,64C128,99.29,99.29,128,64,128z M64,10   c-29.776,0-54,24.224-54,54c0,29.775,24.224,54,54,54c29.775,0,54-24.225,54-54C118,34.224,93.775,10,64,10z"/></g><g><path d="M46.001,40.51c0-3.523,2.489-4.954,5.534-3.179L91.718,60.77c3.044,1.775,3.044,4.68,0,6.457L51.534,90.668   C48.49,92.443,46,91.014,46,87.49L46.001,40.51L46.001,40.51z"/></g></svg>
  </div>
</div>

svg:hover {
  fill: #ff0000;
}

2 个答案:

答案 0 :(得分:2)

在这种情况下是没问题。使用 Adjacent sibling selector

&#13;
&#13;
svg:hover {
  fill: #ff0000;
}

.outer img:hover + div svg {
  fill: green;
}
&#13;
<div class="outer">
  <img src="https://i.pinimg.com/originals/11/94/f3/1194f3b0cb86afdf0d610e7b0b105826.png" />
  <div>
      <svg enable-background="new 0 0 128 128" height="128px" id="Layer_1" version="1.1" viewBox="0 0 128 128" width="128px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><path d="M64,128C28.71,128,0,99.29,0,64C0,28.71,28.71,0,64,0c35.29,0,64,28.71,64,64C128,99.29,99.29,128,64,128z M64,10   c-29.776,0-54,24.224-54,54c0,29.775,24.224,54,54,54c29.775,0,54-24.225,54-54C118,34.224,93.775,10,64,10z"/></g><g><path d="M46.001,40.51c0-3.523,2.489-4.954,5.534-3.179L91.718,60.77c3.044,1.775,3.044,4.68,0,6.457L51.534,90.668   C48.49,92.443,46,91.014,46,87.49L46.001,40.51L46.001,40.51z"/></g></svg>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

也许你想要这样的东西:

img:hover + div svg {
  fill: #ff0000;
}

其中+我所谓的邻居选择器虽然这个只有当两者坐在一起时才有效。

希望有所帮助

相关问题