悬停父元素时如何更改子元素的不透明度

How to change opacity of child-element when hovering his parent

<section class="album" role="listitem" onmouseover="this.albumHeader.style.opacity = 0.6">
    <a href="@HrefHelper.ToAlbum(album.Title, 0)">
        <img src="@albumPreview.GenerateSrcHTML()" height="@albumPreview.PreviewHeight" width="@albumPreview.PreviewWidth" />
    </a>
    <header id="albumHeader">
        <p>@album.Title</p>
    </header>
</section>

这个 JS 代码: this.albumHeader.style.opacity = 0.6 为什么是错误的:"Uncaught TypeError: Cannot read property 'style' of undefined"。这个想法是当用户悬停 <section class="album"... 时,内部的 <header>(默认情况下为 opacity:0.0)变得可见。我该如何解决?

您可以设置以下样式:

.parent:hover .child {
   opacity: 0.5;
}

当然,把选择器换成你自己的。

onmouseover="document.getElementById('albumHeader').style.opacity = 0.6"

请注意,不透明度将保持为 0.6,除非您在鼠标移出时也更改它。 css 解决方案可能更易于维护。

根据您在@GMchris 回答的评论中提出的问题,这里有一个动画示例:

section.album header {
  opacity: 0;
  transition: opacity 0.25s ease-in-out;
}

section.album:hover > header {
  opacity: 0.6;
}

Plunker 示例:click here