CSS YYDS! 基于Ant Design实现自定义下拉选择器

1,546 阅读1分钟

lufei.webp

先看实现效果图

{E93A24AF-1171-41D1-AF52-DA1187BEC770}.bmp

为什么做:

程序员肯定是产品为驱动,实际又没有现成组件。

怎么做:

本文需要使用css content属性,首先明确一下概念:
以下来自 MDN 中的描述
    CSS 的 content 属性用于在元素的  ::before::after 伪元素中插入内容。使用content 属性插入的内容都是匿名的可替换元素

attr()
    The `attr()` function can be used with any CSS property, but support for properties other than [`content`](https://developer.mozilla.org/en-US/docs/Web/CSS/content) is experimental, and support for the type-or-unit parameter is sparse.

结合使用:
    content: attr(value string)  /* attr() value linked to the HTML attribute value */
将元素的 data-* 属性以字符串形式返回。如果该元素没有 data-* 属性,则返回一个空字符串。区分大小写的属性返回值依赖文挡的语言设定。

废话不多说 上干货!!

// 定义下拉内容数组
let options = [
      {
        id: 1,
        goods: '苹果',
        stockTotal: '651',
      },
      {
        id: 2,
        goods: '香蕉',
        stockTotal: '791',
      },
      {
        id: 3,
        goods: '雪梨',
        stockTotal: '367',
      },
      {
        id: 4,
        goods: '橙子',
        stockTotal: '758',
      },
      {
        id: 5,
        goods: '橙子西瓜瓜瓜瓜瓜瓜瓜瓜瓜瓜',
        stockTotal: '758',
      }
    ]
    
  //Ant Design 下拉框
  <Select onChange={this.handleChange} className={'rc-select-expand'}>
      {
         options.map(item =>(
             <Option key={item.id} 
                 data-stockTotal={item.stockTotal}  
                 data-name={'库存'}  
                 className='rc-select-option-expand'>
                 <span className={'line-ellipsis'}>{item.goods}</span>
             </Option>
         ))
      }
    </Select>
    

1.组件上的data-* 为什么能生效?

Ant Design 源码中 select 是基于 rc-select封装的

antd-select.bmp

再看rc-select文档中又找到了下面一句:

data-attr.bmp

所以很容易通过css 实现咱们要求的效果

.rc-select-expand {
  width: 300px;
}
//处理文字内容过长和自定义内容重叠的样式
.line-ellipsis {
  display: inline-block;
  width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
}
//自定义内容
.rc-select-option-expand::after {
  content: attr(data-name) attr(data-stockTotal);
  color: rgb(230, 128, 13);
}

完结啦 如果文章对小伙伴们有帮助,麻烦点个小心心

文中参考链接:

MDN content 属性

MDN attr()