jQuery:按相对值移动元素

发布于 2024-08-12 05:09:43 字数 54 浏览 3 评论 0 原文

(意思是元素的左值): 移动元素最简单的方法是什么 - 例如向左移动 10px(从当前位置)?

(Meaning an elements left-value):
What's the easiest way to move an element - e.g. 10px to the left (from its current position)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

心碎的声音 2024-08-19 05:09:43

下面是一个使用 jQuery 的简单示例:

$("#el").css({
    left: $("#el").position().left - 10 + "px"
});

注意:您想要移动的元素必须绝对定位或相对定位。

Here is a quick example using jQuery:

$("#el").css({
    left: $("#el").position().left - 10 + "px"
});

Note: the element that you want to move must either be positioned absolutely or relatively.

生来就爱笑 2024-08-19 05:09:43

假设你的元素有 id 'myElement':

$('#myElement').css(
{
  'position': 'relative',
  'left': '-10px'
});

Assuming your element has the id 'myElement':

$('#myElement').css(
{
  'position': 'relative',
  'left': '-10px'
});
温柔嚣张 2024-08-19 05:09:43

从 1.6 开始,您可以在 css() 中使用相对值,因此您可以使用以下内容:

$('#myElement).css( "left", "+=15" );

只要该元素已经具有 left 的定义值并且绝对定位。

参考: http://api.jquery.com/css/

As of 1.6 you can use relative values in css() so you could use this:

$('#myElement).css( "left", "+=15" );

As long as the element already has a defined value for left and is absolutely positioned.

Ref: http://api.jquery.com/css/

涫野音 2024-08-19 05:09:43

jQuery 可能有点过分了,设置 margin-left: -10px 就可以了。

您可以获取元素相对于文档的 offset(): http://docs.jquery.com/CSS/ offset

这会给你左边,顶部等。

然后你可能需要像这样使用 css 来定位元素。

 subMenu.css({
            position: 'absolute',
            zIndex: 5000,
            left: left,
            top: top
        });

It might be that jQuery is overkill and setting margin-left: -10px will do the trick.

You can get an element's offset() relative to the document: 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.

 subMenu.css({
            position: 'absolute',
            zIndex: 5000,
            left: left,
            top: top
        });
等待圉鍢 2024-08-19 05:09:43

由于其他答案都不是真正的 jQuery 风格的解决方案,我将复活这个老问题。

此解决方案可以将所有选定元素移动相对值:

$('.selected').each(function() {
    $(this).css({ left: $(this).position().left - 10 });
});

Since none of the other answers are true jQuery-style solutions, i'll resurrect this old issue.

This solution can move ALL of the selected elements by a relative value:

$('.selected').each(function() {
    $(this).css({ left: $(this).position().left - 10 });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文