简体   繁体   English

用于少编译的 Javascript 函数?

[英]Javascript function for get compiled less?

I have an inline tag ....for example:我有一个内联标签......例如:

<style>
    @body-color:#f00;
    body {
        color:@body-color;
    }
</style>

I need a javascript function to get the compiled css from this tag.我需要一个 javascript 函数来从这个标签中获取编译好的 css。 I know how to compile it using less.我知道如何使用 less 编译它。 What I really need is a function that returns to me the compiled css (as a string).我真正需要的是一个将编译后的 css(作为字符串)返回给我的函数。

It seems a trivial question but I can't find anything online.这似乎是一个微不足道的问题,但我在网上找不到任何东西。 Thx.谢谢。

Using this reference :使用此参考

var styles = document.getElementsByTagName("div"), style;
for (var i = 0; i < styles.length; i++) {
  // A bit more simple, and so we don't have to reference it over and over.
  style = styles[i];

  // A less token, you can remove this if you want to it parse all <style> tags.
  if (!style.hasAttribute("data-less")) return;

  // Render
  less.render(style.innerHTML)
  .then(function(output){

    // Set the parse less (CSS) to the <style> tag.
    style.innerHTML = output.css
  }, function(err){

    // Log error...
    console.log(err);
  });
};

Then your HTML can follow:然后你的 HTML 可以遵循:

<style data-less>
    @body-color:#f00;
    body {
        color:@body-color;
    }
</style>

Here is a JSFiddle ...(Due to JSFiddle's restrictions, I changed "style" to "div" )这是一个 JSFiddle ...(由于 JSFiddle 的限制,我将"style"更改为"div"

I'd also considering wrapping it in the DOMContentLoaded handler too, just to make it a bit more fast.我也考虑将它包装在DOMContentLoaded处理程序中,只是为了让它更快一点。

Solved.... thanks to @Blackhole解决了……感谢@Blackhole

HTML: HTML:

<div>
    <textarea id="in" cols="50" rows="8">
        @we:"bold";

        body{
        font-weight:@we;
        }

    </textarea>
</div>
<div>
    <button>COMPILE</button>
</div>

<div>

    <textarea id="out" cols="50" rows="8">


    </textarea>
</div>

JS: JS:

$("body").ready(function(){
  $("button").click(function(){
    var css = $("#in").val();

    less.render(css, null, function(error, output) {
      $("#out").val(output.css);
    });

  })
})

I've created this pen: link我创建了这支笔:链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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