CSS tranform:translateY from JavaScript

前端 未结 3 902
悲&欢浪女
悲&欢浪女 2021-02-07 11:54

How would I access and change transform: translateY(0px); using the style object from JavaScript, in a similar matter to div.style.background = 50px.

相关标签:
3条回答
  • 2021-02-07 12:18

    In addition to the accepted answer, it is also possible to target the each axis separately - such as in the following example:

    div.style.transform = "translateY(10px)";
    

    Again, the value in the parentheses can be anything that would otherwise work when specified directly in CSS.

    0 讨论(0)
  • 2021-02-07 12:25

    You can pass any transform property as a string.

    HOW?

    It can be done like this;

    div.style.transform = "translate(x,y)"
    

    I find out that if I write

    div.style.transform = "translate(someValue)"
    

    It only affects x axes.

    "translate-y(someValue)" or "translate-x(someValue)"
    

    did not work out.

    Or you can use rotate property;

    div.style.transform = "rotate(50px)".
    

    Try it!

    https://jsfiddle.net/araknafobia/4wtxu0dr/1/

    0 讨论(0)
  • 2021-02-07 12:35

    Alternative solution:

    div.setAttribute('style','transform:translateY(10px)');
    
    0 讨论(0)
提交回复
热议问题