jQuery: Move element by relative value

ぃ、小莉子 提交于 2019-12-10 02:00:46

问题


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


回答1:


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
        });



回答2:


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.




回答3:


Assuming your element has the id 'myElement':

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



回答4:


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/




回答5:


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 });
});


来源:https://stackoverflow.com/questions/1806246/jquery-move-element-by-relative-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!