使用CSS transform时,鼠标悬停时div闪烁问题

4
我正在制作一个位于推文(以及 Facebook 点赞)按钮顶部的 div。我希望当我悬停在 div(按钮)上方时,它会向上移动,这样你就可以实际按下真正的推文按钮。我尝试了以下方法。
HTML:
<div class="tweet-bttn">Tweet</div>         
<div class="tweet-widget">
    <a href="https://twitter.com/share" class="twitter-share-button">Tweet</a>
    <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</div>

CSS:
.tweet-bttn{
    position: relative;
    top: -30px;
    left: -10px;
    display:block;
    opacity: 1;
    width: 80px;
    padding: 10px 12px;
    margin:0px;
    z-index:3;}

.tweet-bttn:hover{
    -webkit-animation-name: UpTweet;
    -moz-animation-name: UpTweet;
    -o-animation-name: UpTweet;
    animation-name: UpTweet;
    -webkit-animation-duration:.5s;
    -moz-animation-duration:.5s;
    animation-duration:.5s;
    -webkit-transition: -webkit-transform 200ms ease-in-out;
    -moz-transition: -moz-transform 200ms ease-in-out;
    -o-transition: -o-transform 200ms ease-in-out;
    transition: transform 200ms ease-in-out;}

@-webkit-keyframes UpTweet {
    0% {
        -webkit-transform: translateY(0);
    }   
    80% {
        -webkit-transform: translateY(-55px);
    }
    90% {
        -webkit-transform: translateY(-47px);
    }
    100% {
        -webkit-transform: translateY(-50px);
    }
    ... and all other browser pre-fixes.
}

我不确定出了什么问题。看起来好像只要我鼠标悬停,它就会移动,但如果我再移动一像素,它就必须进行新的计算,这会导致闪烁。
1个回答

6

我不知道为什么你需要动画,因为你可以使用 transitions 来达到上述效果。

诀窍是在父元素悬停时移动子元素。

演示

div {
    margin: 100px;
    position: relative;
    border: 1px solid #aaa;
    height: 30px;
}

div span {
    position: absolute;
    left: 0;
    width: 100px;
    background: #fff;
    top: 0;
    -moz-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
}

div span:nth-of-type(1) {
/* Just to be sure the element stays above the 
   content to be revealed */
    z-index: 1;
}

div:hover span:nth-of-type(1) { /* Move span on parent hover */
    top: -40px;
}

说明:首先,我们将 span 包裹在一个具有 position: relative; 属性的 div 元素中,然后我们对 span 使用 transition,这将帮助我们平滑地流动 animation,现在我们使用 position: absolute;left: 0;,这将把元素堆叠在一起,然后我们使用 z-index 确保第一个元素覆盖第二个元素。

最后,我们移动第一个 span,我们通过使用 nth-of-type(1) 选择它,它是嵌套在 div 中的其类中的第一个子元素,然后我们分配 top: -40px;,这将在父级 div 悬停时过渡。


嗯,我不知道这个,但它看起来像魔法一样运行良好。非常感谢你!! - Emiel Janson
@EmielJanson 没关系,如果你不知道的话就尝试学习一下 :) 尽管我会编辑我的答案来解释,抱歉我错过了。 - Mr. Alien
@EmielJanson 解释了 :) - Mr. Alien
非常感谢!一切开始变得有意义了。我已经玩了一会儿。 :) - Emiel Janson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接