简体   繁体   中英

Javascript — Add transform : translate to existent style

In a project, I use Javascript to give custom translateY transforms to several elements.

The issue I'm facing right now is about adding a translateY(value) to multiple elements when some of those elements already have a translateX(value) in their CSS style.

So of course, el.style.transform = translateY(value) actually erase transform: translateX(value); CSS property. Is there a way to add/merge a translateY to an existing translateX in plain Javascript?

Thanks in advance

If this style is presented as object:

Object.assign(el.style.transform,translateY(value));

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

It will add to existing object new styles.

If it is string property - use concatenation of string.

More information : https://www.w3schools.com/jsref/jsref_concat_string.asp

So I've finally found a solution using getComputedStyle() function. The following code is looking for any translateY value, if so it apply a different transform style on the targeted element.

let l = window.getComputedStyle(el, null),
    t = l.getPropertyValue('transform')

    // If t return other than "none"
    // Split content into several value
    // The fourth one is the translateX value

    if(t != 'none') {
        let v = t.split('(')[1],
            w = v.split(')')[0],
            x = v.split(',')

        el.style.transform = 'translate(' + x[4] + 'px, -' + d / m + '%)'
    } else {
        el.style.transform = 'translate('+ 0 + 'px, -' + d / m + '%)'                   
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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