The most efficient way to style using pure javascript?

What is the most efficient way to set multiple styles on elements in javascript?

for (i=0;i<=lastSelector;i++) {
var e = mySelector[i],
v = 'opacity 1s';
e.style.WebkitTransition = v;
e.style.MozTransition = v;
e.style.OTransition = v;
e.style.MsTransition = v;
e.style.transition = v;
e.style.opacity = 0;
};
+5
source share
3 answers

To a large extent, you can use the difficult task:

for (i=0;i<=lastSelector;i++) {
  var e = mySelector[i];
  e.style.WebkitTransition =
    e.style.MozTransition =
      e.style.OTransition =
        e.style.MsTransition =
          e.style.transition =
            'opacity 1s';
  e.style.opacity = 0;
}

Since there are several of these properties, where we have vendor-specific versions, you can consider a reuse function that does this, for example:

function setMultiVendorProp(style, propName, value) {
    // Set the non-vendor version
    style[propName] = value;

    // Make first char capped
    propName = propName.substring(0, 1).toUpperCase() + propName.substring(1);

    // Set vendor versions
    style["Webkit" + propName] = value;
    style["Moz" + propName] = value;
    style["O" + propName] = value;
    style["Ms" + propName] = value;

    // Done
    return value;
}

Or use the dashed style instead, as we already use strings, not identifiers:

function setMultiVendorProp(style, propName, value) {
    // Set the non-vendor version
    style[propName] = value;

    // Set vendor versions
    style["-webkit-" + propName] = value;
    style["-moz-" + propName] = value;
    style["-o-" + propName] = value;
    style["-ms-" + propName] = value;

    // Done
    return value;
}

Then:

for (i=0;i<=lastSelector;i++) {
  var e = mySelector[i];
  setMultiVendorProp(e.style, "transition", "opacity 1s");
  e.style.opacity = 0;
}

Side notes:

  • There is no ;after closing }in the operator for.
  • var - , var () ; : , var
+6

:

var i,
    es,
    v = 'opacity 1s';
for (i=0;i<=lastSelector;i++) {
    es = mySelector[i].style;

    es.WebkitTransition = v;
    es.MozTransition = v;
    es.OTransition = v;
    es.MsTransition = v;
    es.transition = v;
    es.opacity = 0;
};

v = 'opacity 1s' , , . v, , JS , .

+2

Perhaps in the function:

function setStyles(styles, element, value)
{
    for(var i=0,l=styles.length;i<l;i++)
        {
            if(p in element.style)
                element.style[p] = value;
        }
    };
}

So you can call:

var s = ['WebkitTransition','MozTransition','OTransition','MsTransition','transition'];
for (i=0;i<=lastSelector;i++) {
    var e = mySelector[i],
    v = 'opacity 1s';
    setStyles(s,e,v);
    e.style.opacity = 0;
};
0
source

All Articles