最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】ReactJS中对于less中的css如何定义变量和自动判断加载不同样式

CSS crifan 3790浏览 0评论

已有代码:

/src/components/notice/index.js

                  <dd>
                    <a onClick={this.handleCancel}>{cancelTitle}</a>
                    <a onClick={this.handleConfirm}>{confirmTitle}</a>
                  </dd>

src/components/notice/style.less

.fs_pup_div dl dd {
    width: 100%;
    height: 0.88rem;
    -webkit-border-radius: 0.24rem;
    border-radius: 0.24rem;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
}
.fs_pup_div dl dd a {
    float: left;
    width: 50%;
    height: 0.88rem;
    line-height: 0.88rem;
    font-size: 0.32rem;
    color: #3d77ce;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
}
.fs_pup_div dl dd a:first-child {
    border-right: 1px solid #c1c1c1;
}

现在已经可以正常显示了,

但是是两个a按钮:确定 取消

此处想要实现,根据传入的参数中,如果没有 取消按钮,只有一个确定按钮

则:

内部的样式,自动加载,使得宽度是100%,且没有那个a:first-child对应的竖线了。

css a first-child

CSS :first-child 选择器

:first-child – CSS | MDN

html – How can I use a not:first-child selector? – Stack Overflow

然后用:

.fs_pup_div dl dd a:not(:first-child) {
    border-left: 1px solid #c1c1c1;
}

实现了:

只有一个a的时候,没有后面的竖线:

但是还存在一个问题:

就是当只有一个a时,宽度的问题

css 条件判断

css less 条件判断

CSS系列——前端进阶之路:初涉Less – 懒得安分 – 博客园

css 判断标签a个数

通过 CSS3 根据子元素数量为其定义不同样式 | Sivan’s Blog

【总结】

然后用对应的css代码实现了动态判断:

.fs_pup_div dl dd {
  /* one items */
  a:first-child:nth-last-child(1){
    float: left;
    // width: 50%;
    width: 100%;
    height: 0.88rem;
    line-height: 0.88rem;
    font-size: 0.32rem;
    color: #3d77ce;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
  }
  /* two items */
  a:first-child:nth-last-child(2),
  a:first-child:nth-last-child(2) ~ a {
    float: left;
    width: 50%;
    height: 0.88rem;
    line-height: 0.88rem;
    font-size: 0.32rem;
    color: #3d77ce;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    border-left: 1px solid #c1c1c1;
  }
}

用less中的变量后,优化为:

.common_button{
  float: left;
  height: 0.88rem;
  line-height: 0.88rem;
  font-size: 0.32rem;
  color: #3d77ce;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
}
.fs_pup_div dl dd {
  /* one items */
  a:first-child:nth-last-child(1){
    .common_button;
    width: 100%;
  }
  /* two items */
  a:first-child:nth-last-child(2),
  a:first-child:nth-last-child(2) ~ a {
    .common_button;
    width: 50%;
    border-left: 1px solid #c1c1c1;
  }
}

(1)一个a,一个按钮:

                  <dd>
                    <a onClick={this.handleConfirm}>{confirmTitle}</a>
                  </dd>

效果:

(2)2个a,2个按钮:

                  <dd>
                    <a onClick={this.handleCancel}>{cancelTitle}</a>
                    <a onClick={this.handleConfirm}>{confirmTitle}</a>
                  </dd>

效果:

转载请注明:在路上 » 【已解决】ReactJS中对于less中的css如何定义变量和自动判断加载不同样式

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.174 seconds, using 22.13MB memory