如何将HTML样式标签提取到CSS

问题描述

我正在尝试从div html中自动提取标签样式的一部分。我有100种样式组合,因此无法手动进行。 这是html样式标签的路径-> css

.rule1 { 
  background-color: rgb(196,143);
}

.rule { 
  background-color: rgb(230,176,18);
}
<div class="line line--big line--active" role="button" 
   style="background: rgb(196,143) none repeat scroll 0% 0%; color: white; opacity: 1;"><span>1</span></div>
<div class="line line--big line--active" role="button"
   style="background: rgb(230,18) none repeat scroll 0% 0%; color: white; opacity: 1;"><span>5</span></div>

注意:此问题并非重复,因为我的代码中没有 style标记 我已经搜索了其他答案,但是它们 zurb链接现在关闭 http://zurb.com/ink/inliner.php 在这里,您需要样式标签JavaScript Regex to Extract Text from Style HTML Tags以及此处: Convert css from html style tag into inline css

解决方法

方法1:extractCSS-在线CSS提取器

extractCSS是一个JavaScript库和在线工具,可让您从HTML文档中提取元素ID,类和内联样式并将其输出为CSS。

注意: 不完全是您要查找的内容,但是如果您不介意复制和粘贴HTML,请尝试此操作。功能不是很多,但是可以完成工作!

http://extractcss.com/

https://github.com/peterlazzarino/Inline-CSS-Extractor

方法2:使用Jquery:

您可以使用一些JS / JQuery代码来提取样式,清除样式,为元素提供ID并添加CSS。检查此示例,您可以进一步扩展它。

HTML:

<style></style>
<div style="background-color: red; height:300px; width:200px;">
<a style="font-weight: bold">Link</a>
</div>

jQuery

$(document).ready(function(){
    var i = 0;
    var css = "";
    $("div,a").each(function(){
        $(this).attr("id","st-"+i);
        css += "#"+$(this).attr("id")+"{"+$(this).attr("style")+"}";
        $(this).removeAttr("style");
        i++;
    });
    $("style").html(css);
});
,

如果您确实需要使用simplehtmldom提取此内容:


对于

<style>
...
</style>

使用:

$css = $html->find('style')->innertext;

对于

<div style="background:blue; color:white;"></div>

使用:

$css = $html->find('div[style]')->style;

如果有多个具有div的{​​{1}}或多个style,则可以使用<style>在它们之间循环。


要解析样式:

在PHP中:

foreach

在JS中

$s = 'background:blue; color:white;';

$results = [];
$styles = explode(';',$s);

foreach ($styles as $style) {
    $properties = explode(':',$style);
    if (2 === count($properties)) {
        $results[trim($properties[0])] = trim($properties[1]);
    }
}

var_dump($results);

https://jsfiddle.net/zyfhtwj2/

,

将此代码段与 PURE JS 一起使用

function extract(html) {
  let m= html.match(/class=(".*?"|'.*?')/g)||[];            // class list
  let c= m.map(c=>c.replace(/class=("|')/,'').slice(0,-1)); // only names
  let dedup= [...new Set(c.map(x=>x.split` `).flat())];     // del duplicates

  output.value = dedup.reduce((a,c) => a+=`.${c} {\n}\n\n`,'')
}
<textarea id="inp" cols="70" rows="4" placeholder="Paste html"></textarea>
<br><button onclick="extract(inp.value)">Extract CSS!</button><br><br>
<textarea id="output" cols="70" rows="4"></textarea>