简体   繁体   English

如何在 css 中不初始化的情况下获取左值?

[英]how to get left value without initializing in css?

Basically I need to identify, how far is an element from left corner in pixel while the element style in css is left:auto基本上我需要确定,当 css 中的元素样式为left:auto时,元素距离左角像素有多远

eg:例如:

<span id='span1'>
   <span id='child1'>hello there </span>
   <span id='child2'>get left value of this DOM</span>
</span>

CSS: CSS:

#child1{
  background:red;  
}
#child2{
  background: green;
}

is there anyway to find out the left value of child2 in either javascript or jquery?无论如何要在 javascript 或child2中找出 child2 的左值?

DEMO: https://jsfiddle.net/7wp5fc6r/演示: https://jsfiddle.net/7wp5fc6r/

With Javascript you can get this value and more with getBoundingClientRect() this is the documentation of this method, this is an example:使用 Javascript,您可以使用 getBoundingClientRect() 获取此值和更多信息, 这是此方法的文档,这是一个示例:

 const childTwo = document.getElementById("child2"); const leftSpace = childTwo.getBoundingClientRect().left; console.log("space in pixels", leftSpace)
 #child1{ background:red; } #child2{ background: green; }
 <span id='span1'> <span id='child1'>hello there </span> <span id='child2'>get left value of this DOM</span> </span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM