how to change value dynamically variable

最后都变了- 提交于 2019-12-11 08:57:40

问题


how to use dynamically dotless variables. I mean how to assign value dynamically in dotless file. Is there any way?

style.less file contain

@url_image: 

#head{ background: url(@url_image) no-repeat left top white;}

How can I assign a value at runtime?


回答1:


When you say change dynamically in .less file, I am not sure why you wanna just change it in less file. If you just change it in .less file, you'll have to compile the file in order to navigative the change to style.min.css and style.css files, which you can't do programmatically.

This is what you can do:

 $('#head').css('background-image', "url("new-source");

So jquery/javascript is your best bet




回答2:


There are a number of ways to do this. In my case, both the less content and dynamic parameters are stored in the DB. You can do something like this if you want to change a hex code color for example:

var parser = new dotless.Core.Parser.Parser();
var env = new dotless.Core.Parser.Infrastructure.Env { Compress = true, Debug = true, KeepFirstSpecialComment = false, DisableVariableRedefines = false };
var tree = parser.Parse(css.Detail.Text, null);

foreach (var key in layout.LessDetails.CurrentValues.Keys)
{
   var rule = tree.Variable("@" + key, tree);

   if (rule != null)
   {
      string value = layout.LessDetails.CurrentValues[key];

      if (value != null && value.StartsWith("#"))
      {
         rule.Value = new dotless.Core.Parser.Tree.Color(value.TrimStart('#'));
      }
   }
}

css.Detail.GeneratedText = tree.ToCSS(env);

This isn't an end all solution since there are many other types of parameters, but it should lead you in the right direction. Look in the dotless.Core.Parser.Functions for useful information on the various options.

Alternatively, there is another simple option. With the code above, you can simply append the changed variables to the end of the css.Detail.Text string. This is actually how the modifyVars method works in the less.js file. By adding the parameters again at the end, it overrides the previous set values.




回答3:


This can be done if you manually parse and output the dotless file.

var config = DotlessConfiguration.GetDefaultWeb();
config.DisableVariableRedefines = true;

string less = File.ReadAllText(fileName);
StringBuilder sb = new StringBuilder(less);
sb.AppendLine(string.Format("{0}: {1};", "@url_image", "image.jpg"));

return LessWeb.Parse(sb.ToString(), config);


来源:https://stackoverflow.com/questions/17276966/how-to-change-value-dynamically-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!