jQuery:按相对值移动元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1806246/
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
jQuery: Move element by relative value
提问by Fuxi
(Meaning an elements left-value): What's the easiest way to move an element - e.g. 10px to the left (from its current position)?
(意味着元素左值):移动元素的最简单方法是什么 - 例如向左移动 10px(从其当前位置)?
采纳答案by Mark Holland
It might be that jQuery is overkill and setting margin-left: -10px will do the trick.
可能是 jQuery 有点矫枉过正,设置 margin-left: -10px 就可以了。
You can get an element's offset() relative to the document: http://docs.jquery.com/CSS/offset
您可以获得相对于文档的元素的 offset():http: //docs.jquery.com/CSS/offset
That'd give you the left,top,etc.
那会给你左边,顶部等。
Then you might have to position the element using the css like so.
然后您可能必须像这样使用 css 定位元素。
subMenu.css({
position: 'absolute',
zIndex: 5000,
left: left,
top: top
});
回答by devongovett
Here is a quick example using jQuery:
这是一个使用 jQuery 的快速示例:
$("#el").css({
left: $("#el").position().left - 10 + "px"
});
Note: the element that you want to move must either be positioned absolutely or relatively.
注意:要移动的元素必须绝对定位或相对定位。
回答by Lior Cohen
Assuming your element has the id 'myElement':
假设您的元素具有 id 'myElement':
$('#myElement').css(
{
'position': 'relative',
'left': '-10px'
});
回答by bloke_zero
As of 1.6 you can use relative values in css()
so you could use this:
从 1.6 开始,您可以使用相对值,css()
因此您可以使用它:
$('#myElement).css( "left", "+=15" );
As long as the element already has a defined value for left
and is absolutely positioned.
只要元素已经有一个定义的值left
并且是绝对定位的。
回答by ZPiDER
Since none of the other answers are true jQuery-style solutions, i'll resurrect this old issue.
由于其他答案都不是真正的 jQuery 风格的解决方案,我将重新讨论这个老问题。
This solution can move ALL of the selected elements by a relative value:
此解决方案可以通过相对值移动所有选定元素:
$('.selected').each(function() {
$(this).css({ left: $(this).position().left - 10 });
});