jquery 中心响应动画
jquery animate with center responsive
我正在尝试使用 jquery 和 .css 将方框动画化到屏幕宽度的中心,这将响应浏览器大小调整,但我似乎无法将其设置为在不刷新浏览器的情况下直接在中心响应。这是代码:
<div class="box"></div>
.box {
position: absolute;
border: 1px solid red;
width: 300px;
height: 300px;
}
$(function(){
$(".box").css({left: $(window).width() / 2 - $(".box").width() / 2})
.animate({left: '-=0%', top: '100px'},700);
});
我尝试使用 .css({left:'50%'})
来响应浏览器大小,但现在框没有居中。
您可以使用这个 css 示例居中:
http://www.thesitewizard.com/css/center-div-block.shtml
代码片段:
#box{
...
margin-left: auto ;
margin-right: auto ;
}
因为你正在使用盒子。我相信您想要模态 window 之类的东西。因此,您可以为此使用 jquery UI :
https://jqueryui.com/dialog/
如果您仍然需要使用 jQuery 的样式,您可以尝试再次使用左侧 .css({left:'50%'})
然后添加负边距 50% 的方框 .css({marginLeft: ($('.box').width() / 2)*-1})
so动画代码总结
$(".box").css({left: $(window).width() / 2 - $(".box").width() / 2})
.animate({left: '50%', marginLeft: ($(".box").width()/2)*-1, top: '100px'},700);
根据我在评论中提到的对您问题的理解,这是您可以使用的解决方案。
$(function(){
$(".box").css({left:'50%',transform:'translateX(-50%)'}).animate({top:'100px'},700);
});
我正在尝试使用 jquery 和 .css 将方框动画化到屏幕宽度的中心,这将响应浏览器大小调整,但我似乎无法将其设置为在不刷新浏览器的情况下直接在中心响应。这是代码:
<div class="box"></div>
.box {
position: absolute;
border: 1px solid red;
width: 300px;
height: 300px;
}
$(function(){
$(".box").css({left: $(window).width() / 2 - $(".box").width() / 2})
.animate({left: '-=0%', top: '100px'},700);
});
我尝试使用 .css({left:'50%'})
来响应浏览器大小,但现在框没有居中。
您可以使用这个 css 示例居中: http://www.thesitewizard.com/css/center-div-block.shtml
代码片段:
#box{
...
margin-left: auto ;
margin-right: auto ;
}
因为你正在使用盒子。我相信您想要模态 window 之类的东西。因此,您可以为此使用 jquery UI : https://jqueryui.com/dialog/
如果您仍然需要使用 jQuery 的样式,您可以尝试再次使用左侧 .css({left:'50%'})
然后添加负边距 50% 的方框 .css({marginLeft: ($('.box').width() / 2)*-1})
so动画代码总结
$(".box").css({left: $(window).width() / 2 - $(".box").width() / 2})
.animate({left: '50%', marginLeft: ($(".box").width()/2)*-1, top: '100px'},700);
根据我在评论中提到的对您问题的理解,这是您可以使用的解决方案。
$(function(){
$(".box").css({left:'50%',transform:'translateX(-50%)'}).animate({top:'100px'},700);
});