我正在努力使欢迎文本从我的网站上的图像上方的左侧移动到中心。我需要帮助使用jQuery移动的文本与中心对齐。
我的jQuery:
$(document).ready(function(){
$('.box:first').animate({bottom: '', left: '', }, 2400)
})
答案 0 :(得分:0)
如果您希望文本在中心完美对齐,您最好的选择是直接设置变换位置而不是位置。换句话说,元素的真实位置将是转换的中心。这具有更好的浏览器性能的额外好处。除此之外的一步将是使用CSS来制作动画。请考虑以下事项:
$(document).ready(function() {
$('.box').addClass('active');
});
.box-container {
text-align: center;
}
.box {
display: inline-block;
background: black;
width: 40px;
height: 40px;
-webkit-transform: translateX(-200%);
-ms-transform: translateX(-200%);
transform: translateX(-200%);
transition: transform 0.4s ease-in-out;
}
.box.active {
-webkit-transform: translateX(0%);
-ms-transform: translateX(0%);
transform: translateX(0%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="box-container">
<div class="box"></div>
</div>
通过上面的例子,它将以完全相同的方式动画,而不使用jQuery,这是性能的理想选择。
答案 1 :(得分:0)
首先,您要使用left:50%
将项目移动到屏幕的中间位置,然后将文本完全放在中间,以便将宽度调整为宽度的一半:
$("#test").animate({left:'50%', marginLeft:('-'+$('#test').width()/2)+'px'}, 2400);
$("#test").animate({left:'50%', marginLeft:('-'+$('#test').width()/2)+'px'}, 2400);
#test{position: relative;}
#box{ width: 100px; height: 100px; border: 1px solid black; margin: auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="test">hello</span>
<div id="box"></div>
答案 2 :(得分:-1)
试试这个
$(function(){
$('.box').animate({
left: ($(window).innerWidth() / 2) - $('.box').width() + 'px'
}, 2400);
});
.box {
width: 50px;
height: 50px;
background-color: black;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>