The difference between setLeft and style.left

The difference between off bold style setLeft and style.left

offsetLeft gets the left margin relative to the parent object
left Gets or sets the left margin relative to the parent object with positioning properties (position is defined as relative)

If the position of the parent div is defined as relative and the position of the child div is defined as absolute, then the value of style.left of the child div is relative to the value of the parent div,
which is the same as offsetLeft, the difference is:

  1. style.left returns a string, such as 28px, and offsetLeft returns a value of 28. If you need to calculate the obtained value,
    it is more convenient to use offsetLeft.
  2. style.left is read-write, offsetLeft is read-only, so to change the position of the div, you can only modify style.left.
  3. The value of style.left needs to be defined in advance, otherwise the value obtained is empty. And it must be defined in html. I have experimented. If it is defined in
    css, the value of style.left is still empty. This is the problem I encountered at the beginning, and the value of style.left is always not available.

offsetLeft can still be obtained, no need to define the position of the div in advance

Guess you like

Origin blog.csdn.net/weixin_43465609/article/details/106241112