如何为.box类div添加鼠标悬停滑动动画(含已有过渡样式场景)
Hey there! Let's tackle your two CSS animation questions one by one, nice and clear.
box的div添加鼠标悬停滑动动画效果 First off, your slide animation uses left and top properties to move the element—but these won't work unless the box has a position value set (like relative, absolute, or fixed). Without positioning, the browser doesn't know where to calculate the offsets from.
Here's the full working code:
.box { background-color: red; width: 70px; height: 70px; /* Critical: Add positioning for left/top to work */ position: relative; } @keyframes slide { 0% { left: 0; top: 0; } 50% { left: 244px; top: 100px; } 100% { left: 488px; top: 0; } } /* Apply the animation when hovering */ .box:hover { animation: slide 2s linear forwards; /* The `forwards` value keeps the element at the animation's final state instead of snapping back immediately when hover ends */ }
If you don't want the element to stay at the end position, just remove the forwards keyword—it'll reset to the starting position once you stop hovering.
box添加鼠标悬停滑动动画 First, let's fix a tiny syntax error in your existing transition code: transition-delay: 2s, ; has an extra comma with no value after it, which breaks the entire transition declaration. We'll clean that up first.
Good news: CSS transitions and animations can coexist perfectly! You just need to add the animation to the :hover state while keeping your existing transition rules. Here's the updated code:
.box { background-color: red; width: 70px; height: 70px; /* Fixed the transition-delay syntax error */ transition-property: background, color; transition-duration: .2s, 4s; transition-timing-function: linear, ease-out; transition-delay: 2s; /* Still need positioning for the slide animation */ position: relative; } @keyframes slide{ 0% { left: 0; top: 0; } 50% { left: 244px; top: 100px; } 100% { left: 488px; top: 0; } } /* Hover state triggers both transition and animation */ .box:hover { background-color: yellow; /* Triggers the background color transition */ animation: slide 2s linear forwards; }
When you hover over the box, it'll slide per your slide animation and smoothly change background color according to your existing transition settings. No conflicts here!
内容的提问来源于stack exchange,提问作者Deke

