悬停触发显示播放的隐藏视频无法添加CSS过渡效果,如何修改实现淡入效果?
Hey there! You’re totally right about the hidden attribute — it doesn’t support CSS transitions because it’s an all-or-nothing state. To get that smooth fade-in effect you want, we’ll swap out hidden for animatable CSS properties like opacity and visibility instead. Here’s a revised version of your code that works perfectly:
Step 1: Update the HTML
First, remove the hidden attribute from your video tag — we’ll handle visibility entirely with CSS now. I also renamed duplicate IDs to avoid bugs (having two elements with the same id can break your JS):
<div style="overflow: hidden"> <video id="Hvideo" width="700" height="100%" controls muted loop> <source src="https://www.w3schools.com/jsref/movie.mp4" type="video/mp4"> <source src="https://www.w3schools.com/jsref/movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> <div id="HtextContainer"> <button id="HtextBtn" onmouseover="PlayH()" onmouseout="PauseH()">HVAC</button> </div> <script> // Updated JS below </script> </div>
Step 2: Add Transition-Ready CSS
We’ll set an initial transparent/invisible state for the video, then define a transition for smooth animation. A custom class will handle toggling the video to visible:
#HtextContainer { background: none; border: none; font-size: 50px; padding-bottom: 30px; position: relative; top: 10px; left: 30px; overflow: hidden; } #Hvideo { position: absolute; top: 0%; right: -20%; overflow: hidden; /* Initial hidden state */ opacity: 0; visibility: hidden; /* Smooth fade transition (adjust 0.5s to change speed) */ transition: opacity 0.5s ease, visibility 0.5s ease; } #Hvideo.show-video { /* Visible state to trigger transition */ opacity: 1; visibility: visible; } #Hvideo::-webkit-media-controls-enclosure{ display: none; overflow: hidden; }
opacity: 0makes the video fully transparentvisibility: hiddenensures the video doesn’t block mouse events when invisible- The
transitionproperty tells the browser to animate changes toopacityandvisibilityover 0.5 seconds
Step 3: Adjust the JavaScript
Instead of toggling the hidden attribute, we’ll add/remove our show-video class to trigger the transition:
const videoBtn = document.getElementById("HtextBtn"); const hvacVideo = document.getElementById("Hvideo"); function PlayH() { if (hvacVideo.paused) { hvacVideo.classList.add("show-video"); hvacVideo.play(); } } function PauseH() { hvacVideo.pause(); hvacVideo.classList.remove("show-video"); }
Want a Slide-In Effect Instead?
If you prefer a slide-in over a fade, just add a transform property to the transition. For example:
#Hvideo { /* ... existing styles ... */ transform: translateX(50px); transition: opacity 0.5s ease, visibility 0.5s ease, transform 0.5s ease; } #Hvideo.show-video { /* ... existing styles ... */ transform: translateX(0); }
This will make the video slide in from the right as it fades in!
内容的提问来源于stack exchange,提问作者Tim

