User defined functions with LessCSS?

最后都变了- 提交于 2019-12-01 16:50:56

As far as I know, there's no property argument: you must write it down.

That is, a function will return a calculated value or instruction(s) (property/ies and calculated values).

There aren't thousands of properties in CSS, it's not a CMS with hundreds of classes and functions, so your list won't be as long as you can imagine. You should use other CSS preprocessors or a backend language to generate your CSS if you want to do such complicated things. Or better keep it simple.
That said, lessphp allows for user functions:

lessphp has a simple extension interface where you can implement user functions that will be exposed in LESS code during the compile. They can be a little tricky though because you need to work with the lessphp type system.

Notice that you also can easily add custom functions to the default Less compiler, which enable you to use the client side less.js compiler for testing and the command line lessc compiler for production.

For Less 1.x

  1. Download and unzip the source from github at: https://github.com/less/less.js/releases/latest
  2. Run npm install
  3. Open the lib/functions.js file
  4. Add your custom function (returncenter() in this example) inside the tree.functions object, for instance as follows:

    tree.functions = {
    returncenter: function() {
    return new(tree.Anonymous)('center');
    },
    //original function below
    }
    
  5. Run grunt dist

After the preceding step you can include dist/less-1.x.x/js in your HTML or compile your Less code with the dist/lessc compiler.

For Less 2.x

  1. Download and unzip the source from github at: https://github.com/less/less.js/archive/master.zip
  2. Run npm install
  3. Create a file caleld lib/less/functions/custom.js and write down the following content into it:

    var Anonymous = require("../tree/anonymous"),
        functionRegistry = require("./function-registry");
    
    functionRegistry.addMultiple({
    returncenter: function() {
    return new(Anonymous)('center');
    }
    });
    
  4. Open the lib/less/function/index.js file and append require("./custom"); to the list of register functions, just before return functions;

  5. Run grunt dist

Now you can use the following Less code:

selector {
property: returncenter();    
}

The preceding Less code will compile into the following CSS code:

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