使用 '-webkit-appearance:none;'阻止苹果搞乱 CSS

Using '-webkit-appearance:none;' to stop apple messing with CSS

所以 Apple/Safari 有自己的 CSS 用于各种元素,例如 <select><button> 标签。

我可以通过使用 -webkit-appearance:none; 来解决这个问题,但是对于我的 <select> 这也删除了我想保留的小下拉箭头。

有没有办法解决这个问题,删除其他额外的样式但保留箭头,或者以跨浏览器一致的方式替换箭头?

根据我的评论,使用 appearance: none 实际上会删除 <select> 元素上的所有 browser/OS-specific 样式。这意味着下拉箭头也将被删除,因为不同的操作系统也会有不同的箭头样式。

您可以做的只是为箭头提供您自己的背景图片。这可以通过在元素的右侧提供足够的填充,然后注入背景图像来完成。

下面的示例使用 SVG arrow icon from Google Material Design as part of the data URI.

select {
  -webkit-appearance: none;
  appearance: none;
  
  /* Add paddings to accommodate arrow */
  padding: 8px;
  padding-right: 30px;
  
  /* Add arrow icon */
  /* Source: https://material.io/tools/icons/?icon=keyboard_arrow_down&style=baseline */
  background-image: url('data:image/svg+xml;charset=utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" xml:space="preserve"><path d="M7.41,8.59L12,13.17l4.59-4.58L18,10l-6,6l-6-6L7.41,8.59z"/><path fill="none" d="M0,0h24v24H0V0z"/></svg>');
  background-position: center right;
  background-repeat: no-repeat;
}
<select>
  <option value="Lorem" selected>Lorem</option>
  <option value="Ipsum">Ipsum</option>
  <option value="Dolor">Dolor</option>
  <option value="Sit">Sit</option>
  <option value="Amet">Amet</option>
</select>

注意:如果您想支持 IE,则必须在您的数据 URI 中使用编码的 SVG 标记,即:

background-image: url('data:image/svg+xml;charset=utf8,&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; width=&quot;24px&quot; height=&quot;24px&quot; viewBox=&quot;0 0 24 24&quot; xml:space=&quot;preserve&quot;&gt;&lt;path d=&quot;M7.41,8.59L12,13.17l4.59-4.58L18,10l-6,6l-6-6L7.41,8.59z&quot;/&gt;&lt;path fill=&quot;none&quot; d=&quot;M0,0h24v24H0V0z&quot;/&gt;&lt;/svg&gt;');