ModifyVars issue when trying to change variables one by one

做~自己de王妃 提交于 2019-12-01 20:59:40

you should call less.refreshStyles(); after passing new value to modifyVars.

You can use the following javascript (depends on jquery) code to pass your form value to modifyVars:

function somethingChanged()
{
    var fields = $( '#variables' ).serializeArray();
    var variables = new Object;
    jQuery.each( fields, function( i, field ) {
       variables['@' + field.name] = field.value;
    });
    less.modifyVars(variables);
    less.refreshStyles();
}   
$('#variables input[type="text"]').change(somethingChanged);
$('#variables').submit(function(e){ e.preventDefault(); somethingChanged();});

The above Javascript code works when the form look like that shown below:

<form id="variables">
    <input type="text" name="backgroundcolor" value="red">
    <input type="text" name="fontcolor" value="green">
</form> 

The Less file should look like that shown beneath:

@backgroundcolor: red;
@fontcolor: green;

    body {
    background-color: @backgroundcolor;
    color: @fontcolor;
    }

When i call my Less file call test.less the complete HTML can look like that shown below:

<!DOCTYPE html>
<html>
<head>
<title>Less example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet/less" type="text/css" href="test.less">
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/1.7.4/less.min.js"></script>
</head>
<body>
    <p>Colored text</p>
<form id="variables">
    <input type="text" name="backgroundcolor" value="red">
    <input type="text" name="fontcolor" value="green">
</form> 
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function somethingChanged()
{
    var fields = $( '#variables' ).serializeArray();
    var variables = new Object;
    jQuery.each( fields, function( i, field ) {
       variables['@' + field.name] = field.value;
    });
    less.modifyVars(variables);
    less.refreshStyles();
}   
$('#variables input[type="text"]').change(somethingChanged);
$('#variables').submit(function(e){ e.preventDefault(); somethingChanged();});
</script>
</body>
</html>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!