In jQuery how can I set “top,left” properties of an element with position values relative to the parent and not the document?

前端 未结 7 1038
感情败类
感情败类 2020-12-12 18:43

.offset([coordinates]) method set the coordinates of an element but only relative to the document. Then how can I set coordinates of an element but relative to

7条回答
  •  青春惊慌失措
    2020-12-12 19:13

    To set the position relative to the parent you need to set the position:relative of parent and position:absolute of the element

    $("#mydiv").parent().css({position: 'relative'});
    $("#mydiv").css({top: 200, left: 200, position:'absolute'});
    

    This works because position: absolute; positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static).

提交回复
热议问题