jquery - Convert external CSS to Inline on button press with javascript -
i developing page needs displayed on screen sent out html email.
i have created style in separate (external) css file do.
this page has multiple different templates, sharing same classes styled using css, makes quite long , tedious job go , manually inline css.
i wonder if there's way automatically css , convert inline.
i have done reseach , code test well.
this how far got:
- i can css using request
- i have html of page cleaned (removed unwanted parts)
and i'd automatically inline properties when class found in css , html.
i have made attempt here https://codepen.io/nickhg/pen/wqyzgj?editors=1010
var classmatches, cls, css, cssrule, el, html, i, j, k, l, len, len1, len2, len3, len4, len5, listofclasses, m, n, o, parsedcss, parsedhtml, parser, ref, res, v; css = ".inside1{background:red;}.inside2{background:purple;}"; parser = new cssjs(); parsedcss = parser.parsecss(css); html = $('.outside').html(); parsedhtml = $.parsehtml(html); listofclasses = []; (k = = 0, len = parsedhtml.length; < len; k = ++i) { v = parsedhtml[k]; listofclasses.push(v.classname); } classmatches = []; (k = j = 0, len1 = parsedcss.length; j < len1; k = ++j) { v = parsedcss[k]; (l = 0, len2 = listofclasses.length; l < len2; l++) { cls = listofclasses[l]; if ("." + cls === v.selector) { console.log("matching class - ", v.selector); ref = v.rules; (m = 0, len3 = ref.length; m < len3; m++) { cssrule = ref[m]; res = cssrule.directive + ':' + cssrule.value + ';'; classmatches.push({ "class": cls, css: res }); } } } } console.log(classmatches); (k = n = 0, len4 = parsedhtml.length; n < len4; k = ++n) { v = parsedhtml[k]; debugger; (o = 0, len5 = classmatches.length; o < len5; o++) { el = classmatches[o]; if (v.classname === el["class"]) { if (v.attributes['style'] != null) { v.attributes['style'].value = el.css; } } } } $('.outside').html(parsedhtml);
(the code above compiled version of coffeescript)
but it's not working correctly , should recursive have nested elements well, prefer use library exists (if exists) rather having write own.
any ideas/suggestions?
thanks
at end, if interested, changed template bit used 1 , show/hide required/not required parts.
this made slimmer , easier edit. used ng-style
(yes, i'm using angular) apply style inline.
basically created style in scope object , used way in template:
$scope.style = { class1: {background:"red"}, class2: {background:"yellow"} } <div ng-style="style.class1">...</div> <div ng-style="style.class2">...</div>
i don't approach, works , @ least let me keep style in 1 place if have need edit/change it.
Comments
Post a Comment