动画div从中心到右边(css或jquery)

时间:2015-05-01 17:54:08

标签: javascript jquery html css css3

我需要将此居中(带边距自动)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过渡,但是不能用margin auto做到这一点。我也试过用jquery这样做:

$(document).ready(function() {
	        $( "#submit" ).animate({
	        	marginRight: "10%"
          	}, 500);
      });

它有效,但它的行为很奇怪,因为它会将边距重置为0,然后再向右移动。 我该怎么办?

2 个答案:

答案 0 :(得分:1)

如果我正确地解释了您的问题,这应该有效:

尝试将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/

答案 1 :(得分:0)

我看到了@ guest271314的解决方案,他的javascript对我来说似乎没用,但是他让我知道了calc css函数,所以我用这种方式解决了它:

$(document).ready(function() {    
    $( "#submit" ).animate({
	      	left: "70%"
	}, 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 {
	font-size:2.5rem;
	color:#fcfcfd;
	background: rgba(203, 78, 78, 0.8);
	width:200px;
	margin-top:80px;
	position:relative;
	left:calc(50% - 100px); /* 50% minus half of the width in pixel */
	transition: margin .5s ease-in-out;
}
#submit:hover {
	background: rgba(203, 78, 78, 0.5);
}
 <div id="submit" class="button">Do nothing!</div>