我需要为这个居中(带边距自动)的 div 设置动画:
.button {
border-radius:10px;
padding:10px 5px;
transition:background .4s;
box-shadow:inset 0 -2px 0 0 rgba(0,0,0,0.25);
cursor:pointer;
}
.button:active {
box-shadow:0 0 0 0;
position:relative;
top:2px;
}
#submit {
font-size:2.5rem;
color:#fcfcfd;
background: rgba(203, 78, 78, 0.8);
width:200px;
margin:80px auto 0 auto;
transition: margin .5s ease-in-out;
}
#submit:hover {
background: rgba(203, 78, 78, 0.5);
}
<div id="submit" class="button">Button that doesn't do anything.</div>
但问题是:我不能设置百分比宽度,因为如果我这样做,调整浏览器的大小,文本将从按钮背景中跑出来,我不想为文本设置任何媒体查询。 我也尝试过使用 css transition,但它不能使用 margin auto。我也试过用 jquery 这样做:
$(document).ready(function() {
$( "#submit" ).animate({
marginRight: "10%"
}, 500);
});
它可以工作,但它的行为很奇怪,因为它将左边的边距重置为 0 并且在它向右移动之后。 我能做什么?
最佳答案
如果我正确解释了你的问题,这应该有效:
尝试将 top:80px;
添加到 #submit
的 CSS 中,并将 left
属性替换为 margin
.animate()
函数的属性。
$(function() {
var button = $("#submit");
button.css(
"left", "calc(" + ((window.innerWidth / 2) - button.width() / 2) + "px)"
)
.animate({
left: ((window.innerWidth) - (button.width() + 50))
}, 500);
});
.button {
border-radius: 10px;
padding: 10px 5px;
transition: background .4s;
box-shadow: inset 0 -2px 0 0 rgba(0, 0, 0, 0.25);
cursor: pointer;
}
.button:active {
box-shadow: 0 0 0 0;
position: relative;
top: 2px;
}
#submit {
position: relative;
font-size: 2.5rem;
color: #fcfcfd;
background: rgba(203, 78, 78, 0.8);
width: 200px;
top: 80px;
/* margin: 80px auto 0 auto; */
transition: left .5s ease-in-out;
}
#submit:hover {
background: rgba(203, 78, 78, 0.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="submit" class="button">Button that doesn't do anything.</div>
关于javascript - 从中心向右动画div(css或jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29992262/