如何将转换应用于具有display:none的元素?

时间:2022-11-28 15:01:38

I have some divs that appear when you hover an image. However, I want to have a transition rather than the images appearing so abruptly. I'm trying to avoid javascript if possible.

当你悬停图像时,我会出现一些div。但是,我希望有一个过渡而不是突然出现的图像。我试图尽可能避免使用javascript。

img {
display: none
}
p.one:hover + img {
display: block;
}
p.two:hover img {
display: block;
}

http://jsfiddle.net/nmeyf03r/56/

http://jsfiddle.net/nmeyf03r/56/

1 个解决方案

#1


1  

Transitions don't work with display: none. You can't fade in an element that's been removed from the page. Similarly, you can't fade out a display: block element. With display, the element is either in or out.

转换不适用于display:none。您无法淡入已从页面中删除的元素。同样,你不能淡出display:block元素。通过显示,元素可以是in或out。

However, you can still transition your divs with CSS using the visibility, opacity and height properties.

但是,您仍然可以使用可见性,不透明度和高度属性使用CSS转换div。

HTML

HTML

<p class="one">HOVER OVER ME - IMG IS SIBLING</p>
     <img src="http://www.placecage.com/100/100">
<p class="two">HOVER OVER ME -IMG IS CHILD</p>
    <img src="http://www.placecage.com/100/100">

CSS

CSS

img {
    visibility: hidden;
    opacity: 0;
    height: 0;
    transition: height .5s linear, opacity .5s linear;
}

p.one:hover + img {
    visibility: visible;
    opacity: 1;
    height: 100px;
    transition-delay: 0s;
}

p.two:hover + img {
    visibility: visible;
    opacity: 1;
    height: 100px;
    transition-delay: 0s;
}

Here's your demo, updated with the code above:
http://jsfiddle.net/nmeyf03r/58/

这是您的演示,使用上面的代码更新:http://jsfiddle.net/nmeyf03r/58/

#1


1  

Transitions don't work with display: none. You can't fade in an element that's been removed from the page. Similarly, you can't fade out a display: block element. With display, the element is either in or out.

转换不适用于display:none。您无法淡入已从页面中删除的元素。同样,你不能淡出display:block元素。通过显示,元素可以是in或out。

However, you can still transition your divs with CSS using the visibility, opacity and height properties.

但是,您仍然可以使用可见性,不透明度和高度属性使用CSS转换div。

HTML

HTML

<p class="one">HOVER OVER ME - IMG IS SIBLING</p>
     <img src="http://www.placecage.com/100/100">
<p class="two">HOVER OVER ME -IMG IS CHILD</p>
    <img src="http://www.placecage.com/100/100">

CSS

CSS

img {
    visibility: hidden;
    opacity: 0;
    height: 0;
    transition: height .5s linear, opacity .5s linear;
}

p.one:hover + img {
    visibility: visible;
    opacity: 1;
    height: 100px;
    transition-delay: 0s;
}

p.two:hover + img {
    visibility: visible;
    opacity: 1;
    height: 100px;
    transition-delay: 0s;
}

Here's your demo, updated with the code above:
http://jsfiddle.net/nmeyf03r/58/

这是您的演示,使用上面的代码更新:http://jsfiddle.net/nmeyf03r/58/