将内联CSS转换为外部CSS

问题描述 投票:0回答:1

我需要将内联CSS转换为外部CSS,有人知道怎么做吗?如何分隔html和css并将它们插入div-html和div-css。

例如:

来自此:

<div id="one" style="background-color:green;width:50px;height:50px;">Div one</div>

对此:

<div id="one">Div one</div>
#one{
    background-color:green;
    width:50px;
    height:50px;
}

这是它的外观:

<div id="container"
    <div id="one" style="background-color:green;width:50px;height:50px;">Div one</div>
    <div id="two" style="background-color:red;width:150px;height:150px;">
          <div id="three" style="background-color:blue;width:50px;height:50px;">Div three</div>
    </div>
</div>

<div id="html"></div>
<div id="css"></div>
<button onclick="myFunction()" >click</button>
<script>
function myFunction(){
    var x = document.getElementById("container").innerHTML
    var html =
    var css =

    document.getElementById("html").innerHTML = html;
    document.getElementById("css").innerHTML = css;
}
</script>
javascript html css inline converters
1个回答
1
投票

也许是这样?

let style = '';

function myFunction() {
  document.querySelectorAll('div').forEach(e => {
    if (e.getAttribute('style')) {
      style += `
    #${e.getAttribute('id')}{${formatStyle(e.getAttribute('style'))}
    }`;
      e.removeAttribute('style');
    }
  });
  document.querySelector('#css').innerHTML = style;
  createStyleTag(style);
}

function formatStyle(style) {
  let tmp = '';
  let styles = style.split(';');
  styles.forEach(e => {
    if (e)
      tmp += `
       ${e};`;
  })
  return tmp;
}

function createStyleTag(css) {
  var head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

  head.appendChild(style);

  style.type = 'text/css';
  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
}
#css {
  white-space: pre;
}
<div id="container">
  <div id="one" style="background-color:green;width:50px;height:50px;">Div one</div>
  <div id="two" style="background-color:red;width:150px;height:150px;">
    <div id="three" style="background-color:blue;width:50px;height:50px;">Div three</div>
  </div>
</div>

<div id="html"></div>
<div id="css"></div>
<button onclick="myFunction()">click</button>

0
投票

您可以使用Visual Code和编辑器,并且有大量的扩展程序可以满足您的需求。

© www.soinside.com 2019 - 2024. All rights reserved.