Access CSS3 to translate translation offsets using JavaScript

I use JavaScript to move an element using the translate function of the -webkit-transform property:

 node.style.WebkitTransform = "translate(" + leftPos + "px, 0px)" 

The leftPos value leftPos computed at runtime.

In another method, I want to move this node from its current position. This method does not know the value of lastPos .

How can I get the leftPos value from the DOM without tracking it?

One obvious solution is to analyze the value of the property:

 node.style.WebkitTransform; // returns "translate(-Xpx, 0px)" 

I can make it out, but it does not seem optimal.

+4
source share
2 answers

I would not do it this way, personally - see reservations about why.

However, it is possible. Interfaces are not very well known, so I will explain how this is done for everyone who is interested.

How to do it

You can access the property directly by minimizing through the DOM interfaces for CSS transformations, in particular CSSTransformValue ( WebKitCSSTransformValue in WebKit), with which you can access the parameters of the transformation functions:

 leftPos = node.style.getPropertyCSSValue('-webkit-transform')[0][0].getFloatValue(CSSPrimitiveValue.CSS_PX); 

Let me break it down and take a look at the relevant interfaces:

Warnings

  • My personal preference is to just save the property somewhere (like the data-* attribute in the element) or even use a regular expression for the value of the property and maybe use the WebKit animation to make a heavy lift for you. Access to it it is thus tedious, messy and involves hitting several less durable tracks through the DOM.

  • This method does not work in Firefox, even if you use -moz-transform . Mozilla only supports getPropertyCSSValue based on the results of getComputedStyle ; this gives you the transformation matrix, in which case you should use window.getComputedStyle(el).getPropertyCSSValue('-webkit-transform')[0][4].getFloatValue(CSSPrimitiveValue.CSS_PX) to access the translate-X value. (Assuming that only one transformation is applied.)

  • For years, W3C has been talking about depreciating these interfaces in favor of CSSOM . Progress on this was stalled at the time of writing , but this, of course, is no longer an argument for exclusion!

+5
source

Maybe jQuery can help you: jQuery: offset () .

EDIT: jQuery: position () is what you want

-4
source

Source: https://habr.com/ru/post/1389859/


All Articles