Javascript 如何将整个 div 元素向上移动 x 像素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7152550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to move an entire div element up x pixels?
提问by codecompleting
I want to reposition an entire div and its contents up about 10-15 pixels.
我想将整个 div 及其内容重新定位约 10-15 像素。
How can I do this?
我怎样才能做到这一点?
Note: this is slider element, so when I click a button the slider slides down. Once it is finished I want to reposition it up about 15 pixels.
注意:这是滑块元素,因此当我单击按钮时,滑块会向下滑动。完成后,我想将其重新定位约 15 像素。
回答by Jasper
$('#div_id').css({marginTop: '-=15px'});
This will alter the css for the element with the id "div_id"
这将更改 id 为“div_id”的元素的 css
To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):
为了获得您想要的效果,我建议将上面的代码添加到动画中的回调函数中(这样在动画完成后 div 将向上移动):
$('#div_id').animate({...}, function () {
$('#div_id').css({marginTop: '-=15px'});
});
And of course you could animate the change in margin like so:
当然,您可以像这样设置边距变化的动画:
$('#div_id').animate({marginTop: '-=15px'});
Here are the docs for .css()
in jQuery: http://api.jquery.com/css/
以下是.css()
jQuery中的文档:http: //api.jquery.com/css/
And here are the docs for .animate()
in jQuery: http://api.jquery.com/animate/
这是.animate()
jQuery中的文档:http: //api.jquery.com/animate/
回答by gislikonrad
$('div').css({
position: 'relative',
top: '-15px'
});
回答by srinivas
In css add this to the element:
在 css 中将此添加到元素中:
margin-top: -15px; /*for exact positioning */
margin-top: -5%; /* for relative positioning */
you can use either one to position accordingly.
您可以使用其中任何一个来相应地定位。
回答by Mr Heelis
you can also do this
你也可以这样做
margin-top:-30px;
min-height:40px;
this "help" to stop the div yanking everything up a bit.
这个“帮助”可以阻止 div 把所有东西都拉起来一点。