如何为jQuery控制的css进行平滑过渡?

时间:2016-10-04 17:42:28

标签: jquery css

您好我有一个div我想要由jQuery控制中心。我想在点击时将div移动到页面的中心。为此,我设置了一个jQuery函数来通过css影响定位。它工作正常,但它没有顺利过渡,即使我添加了css过渡,它也会立即发生。以下是我到目前为止的代码

这是css:

.footer-active-line {
    height: 10px;
    width: 33.3333333333%;
    -webkit-transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -ms-transition: all .25s ease-in-out;
    -o-transition: all .25s ease-in-out;
    transition: all .25s ease-in-out;
}

这是jQuery:

jQuery(".footer-locations-box2").click(function(){
    jQuery(".footer-active-line").css({ 'right': '0px', 'left': '0', 'margin': '0 auto' })        
});

这段代码有效,div会居中,但过渡并没有开始。有没有人知道如何让过渡顺利进行?

谢谢!

2 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,CSS转换不适用于目标或auto的起始值。它必须以某种方式数字化。话虽这么说,你正在使用margin: 0 auto,因为它会自动调整边距,从而产生居中的错觉。基本上,浏览器在两侧设置相同的边距以适合容器。问题是您已经知道目的地保证金将是什么。您的.footer-active-line设置为容器width: 33.3333333333%;宽度的1/3。您可以使用transform(相对于其应用的元素的宽度)为100%,也可以将边距设置为33%,这相对于偏移的父级。

这是方法一:

jQuery(".footer-locations-box2").click(function(){
    jQuery(".footer-active-line").css({ transform: 'translateX(100%)' });       
});
.footer-active-line {
    background: red;
  
    height: 10px;
    width: 33.3333333333%;
    -webkit-transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -ms-transition: all .25s ease-in-out;
    -o-transition: all .25s ease-in-out;
    transition: all .25s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="footer-active-line">
</div>

<button class="footer-locations-box2">transition</button>

这是方法二:

jQuery(".footer-locations-box2").click(function(){
    jQuery(".footer-active-line").css({ margin: '0 33.33333%' });       
});
.footer-active-line {
    background: red;
  
    height: 10px;
    width: 33.3333333333%;
    -webkit-transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -ms-transition: all .25s ease-in-out;
    -o-transition: all .25s ease-in-out;
    transition: all .25s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="footer-active-line">
</div>

<button class="footer-locations-box2">transition</button>

答案 1 :(得分:0)

您的点击事件可能会扰乱您的动画。尝试对您的处理程序进行此更改

    jQuery(".footer-locations-box2").click(function(e){
        e.preventDefault();
        jQuery(".footer-active-line").css({ 'right': '0px', 'left': '0', 'margin': '0 auto' })        
    });
相关问题