gpt4 book ai didi

javascript - 为居中的 div 设置动画

转载 作者:行者123 更新时间:2023-11-28 14:19:50 24 4
gpt4 key购买 nike

我有一个宽度未知的 div,其父级居中使用

.centered {
left : 0px;
right : 0px;
margin-left : auto;
margin-right : auto;
}

它的最终风格将是

.notCentered {
right : 100%;
margin-right : 20px;
}

我尝试过使用 css3 转换和 jquery-ui switchClass,但是当它从神奇地居中变为不居中时,它一直在抖动。

有什么方法可以轻松地制作动画吗?我知道为什么我正在做的事情不起作用,我想避免手动计算 javascript 中的位置。

我的完整代码在这里

<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="screen">

.container {
position : absolute;
width : 400px;
height : 400px;
background : blue;
}

.centered {
position : absolute;
left : 0px;
right : 0px;
margin-left : auto;
margin-right : auto;
width : 200px;
height : 200px;
background : red;
}

.notCentered {
position : absolute;
right : 100%;
width : 200px;
height : 200px;
background : red;
-webkit-transition : all 2s ease-in-out;
}


</style>
</head>
<body>
<div class="container">
<div class="centered" onclick="this.className = 'notCentered';"></div>
</div>
</body>
</html>

最佳答案

  1. 在转换的两个状态之间,您应该声明将要更改的有效属性
  2. 转换需要在第一个状态中声明,所以它应该在类 .centered 中,它定义了转换的第一个状态,所以尝试像这样改变:

    /* initial state contaning the transition */         
    .centered {
    position : absolute;
    left : 0px;
    right : 0px;
    margin-left : auto;
    margin-right : auto;
    width : 200px;
    height : 200px;
    background : red;
    -webkit-transition : all 2s ease-in-out;
    }

    /* final state containing only the property that will change */
    .notCentered {
    right : 100%;
    }

然后添加类(不要替换)

<div class="container">
<div class="centered" onclick="this.className += ' notCentered';"></div>
</div>

js fiddle :http://jsfiddle.net/AhvNX/

关于javascript - 为居中的 div 设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8652699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com