前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >less中的变量

less中的变量

原创
作者头像
程序员 NEO
发布2023-09-29 07:24:28
发布2023-09-29 07:24:28
3170
举报

什么是变量

和 JS 中的概念基本一样

less 中定义变量的格式

@变量名称: 值;

代码语言:less
复制
@w: 200px;

less 中使用变量的格式

@变量名称;

代码语言:less
复制
@w;
代码语言:less
复制
@w: 200px;
@h: 400px;
@c: red;

.box1 {
  width: @w;
  height: @h;
  background: @c;
  margin-bottom: 20px;
}

.box2 {
  width: @w;
  height: @h;
  background: @c;
}
image-20210807141308431
image-20210807141308431

和 JS 一样可以将一个变量赋值给另外一个变量,使用格式如下

@变量名称 : @变量名称;

代码语言:less
复制
@w: 200px;
@h: @w;

和 JS 一样 less 中的变量也有 全局变量局部变量 之分

定义在 {} 外面的就是 全局的变量,什么地方都可以使用

image-20210807141731351
image-20210807141731351

定义在 {} 里面的就是 局部变量,只能在 {} 中使用

代码语言:less
复制
@w: 200px;
@h: 400px;
@c: red;

.box1 {
  @bgColor: blue;
  width: @w;
  height: @h;
  background: @bgColor;
  margin-bottom: 20px;
}

.box2 {
  width: @w;
  height: @h;
  background: @c;
}
image-20210807141918904
image-20210807141918904

如果定义在 {} 中的变量在其它的 {} 中使用会报错,如下,首先在编译层面就过不去

image-20210807142125050
image-20210807142125050
代码语言:less
复制
@w: 200px;
@h: 400px;
@c: red;

.box1 {
  @bgColor: blue;
  width: @w;
  height: @h;
  background: @bgColor;
  margin-bottom: 20px;
}

.box2 {
  width: @w;
  height: @h;
  background: @bgColor;
}
image-20210807142101624
image-20210807142101624

注意点:less 中的变量是 延迟加载 的,写到后面也能在前面使用

image-20210807142234934
image-20210807142234934
代码语言:less
复制
@w: 200px;
@h: 400px;

.box1 {
  @bgColor: blue;
  width: @w;
  height: @h;
  background: @bgColor;
  margin-bottom: 20px;
}

.box2 {
  width: @w;
  height: @h;
  background: @c;
}

@c: red;
image-20210807151042953
image-20210807151042953

和 JS 一样不同作用域的变量不会相互影响,只有相同作用域的变量才会相互影响

image-20210807151619652
image-20210807151619652
代码语言:less
复制
@w: 200px;
@h: 400px;
@c: red;

.box1 {
  @c: yellow;
  width: @w;
  height: @h;
  background: @c;
  margin-bottom: 20px;
  @c: pink;
}

.box2 {
  width: @w;
  height: @h;
  background: @c;
}

和 JS 一样在访问变量时会采用就近原则

image-20210807151328223
image-20210807151328223
代码语言:less
复制
@w: 200px;
@h: 400px;
@c: red;

.box1 {
  @c: yellow;
  width: @w;
  height: @h;
  background: @c;
  margin-bottom: 20px;
}

.box2 {
  width: @w;
  height: @h;
  background: @c;
}

我正在参与2023腾讯技术创作特训营第二期有奖征文,瓜分万元奖池和键盘手表

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是变量
  • less 中定义变量的格式
  • less 中使用变量的格式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档