隐藏 select 元素的文本部分

Hide text part of select element

我在边栏中有一个 select 元素。侧边栏可以折叠,这会导致其中的所有内容变为图标。发生这种情况时,我希望 select 仅显示箭头按钮(单击它时仍应打开完整的下拉菜单),但宽度不会低于某个点并且仍会显示一小部分空的白框(据我所知没有连接到任何填充或边距)。有什么办法吗?我能找到的唯一相关问题是关于隐藏按钮。

标记:

<select [ngClass]="{'account-selector': !sidebarCollapsed, 'account-selector-collapsed': sidebarCollapsed}" [(ngModel)]="selectedAccount" (change)="setSelectedAccount()">
    <option *ngFor="let account of accounts" [ngValue]="account" [selected]="account === selectedAccount">{{account.data.Name}}</option>
</select>

CSS:

.account-selector {
    max-width: 90%;
}

.account-selector-collapsed {
    // what goes here?
}

没有 plunker 来查看它的行为,我只能猜测你需要做的是:

.account-selector-collapsed {
    width: calc( 90% - 10px) /*change 10px to suite your need*/
}

我花了很多时间试图让 select 元素有样式。 不幸的是,目前这是不可能的。每个浏览器都有自己的方式来呈现本机 select 框元素,即使您使用 css.

设置样式也是如此

我看到你在使用 Angular 4 (2)。仅使用 <div> 或您想要的任何元素来制作自己的 select 非常简单。

这里是一些实现的例子。

select.component.html:

    <div class="select-options">
      <div
        class="select-option"
        *ngFor="let option of options"
        [attr.data-value]="option.id"
        [class.selected]="option.active"
        [innerText]="option.title"
        (click)="selectOption(option.id);"
      >
      </div>
    </div>

select.component.ts:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.scss']
})
export class SelectComponent implements OnInit {
  @Input() options: Array<any> = [];

  constructor() {}

  ngOnInit() {

  }

  selectOption(optionId) {
    this.options.map(option => period.active = option.id === optionId);
  }
}

使用这个 CSS:

.account-selector-collapsed {
    cursor: pointer;
    width: 15px;
    height: 15px;
    font-size: 0; // hides the text for the current selection
    border: 0;
    background: white; // TODO: replace with an appropriate image
    -moz-appearance: none;
    -webkit-appearance: none;
}
.account-selector-collapsed::-ms-expand {
    display: none;
}

关键是 -moz/webkit-appearance: none;,它本质上将它变成了一个可以自由设置样式的纯文本框,::-ms-expand 在 IE/Edge 上起到了类似的作用。我还没有能够对后者进行太彻底的测试(我正在处理 Mac 而我的 Windows VM 有问题),但从我的能力来看它似乎在那里工作进行测试,绝对适用于其他浏览器。