javascript - 从中心向右动画div(css或jquery)

标签 javascript jquery html css

我需要为这个居中(带边距自动)的 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>

jsfiddle https://jsfiddle.net/jd8eea3e/2/embedded/result/

关于javascript - 从中心向右动画div(css或jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29992262/

相关文章:

javascript - 如何制作一个计数 3 秒的函数

javascript - jQuery 替换和追加

javascript - 如何制作一个用户脚本来更改每个元素的每个 'href' 属性?

使用反向引用的 javascript 模式替换不起作用

jquery - 如何替换我的 ajax 请求 URL 中的 %2F?

javascript - Jquery:将输入值与数组对象进行比较,看看它们是否完全匹配

html - 将文本保持在指定的行数

html - 使 <a> anchor 标记填充列表 <li> 显示 : table-cell

javascript - 将 knexnest 调用拉出到其自己的文件中以防止重复

javascript - 页面加载时自动提交表单