You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用input标签实现带侧边三角标记的自定义搜索栏

实现侧边带三角标记的搜索栏(Input标签)

单纯调整borderRadius做不出这种侧边三角效果,因为三角属于多边形切割的形状,得用下面两种通用方法结合styled-components实现:

方法一:容器+伪元素模拟三角(兼容性好)

给input套一个容器,借助容器的伪元素绘制三角,让容器和input样式衔接成整体:

import styled from 'styled-components';

const SearchContainer = styled.div`
  position: relative;
  display: inline-flex;
  align-items: center;
`;

const SearchInput = styled.input`
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-right: none;
  border-radius: 4px 0 0 4px;
  height: 36px;
  box-sizing: border-box;
`;

// 用伪元素绘制三角
SearchContainer.styled`
  &::after {
    content: '';
    position: absolute;
    right: 0;
    width: 0;
    height: 0;
    border-top: 18px solid transparent;
    border-bottom: 18px solid transparent;
    border-left: 12px solid #ccc;
    /* 填充三角内部背景色,和input一致 */
    &::before {
      content: '';
      position: absolute;
      top: -17px;
      left: -11px;
      border-top: 17px solid transparent;
      border-bottom: 17px solid transparent;
      border-left: 11px solid #fff;
    }
  }
`;

// 使用示例
function SearchBar() {
  return (
    <SearchContainer>
      <SearchInput placeholder="搜索..." />
    </SearchContainer>
  );
}

核心逻辑:利用CSS边框的特性(透明边框+有色边框)画出三角轮廓,再用内层伪元素填充和input相同的背景色,让三角看起来是input的延伸部分。

方法二:clip-path 裁剪容器(简洁现代)

用CSS的clip-path属性直接裁剪容器形状,input填满容器即可实现效果,无需伪元素:

import styled from 'styled-components';

const SearchContainer = styled.div`
  display: inline-block;
  /* 定义左侧圆角+右侧三角的多边形裁剪路径 */
  clip-path: polygon(0 0, calc(100% - 12px) 0, 100% 50%, calc(100% - 12px) 100%, 0 100%, 0 50%);
  border: 1px solid #ccc;
  border-radius: 4px 0 0 4px;
`;

const SearchInput = styled.input`
  width: 100%;
  padding: 8px 12px;
  border: none;
  background: #fff;
  outline: none;
  box-sizing: border-box;
  height: 36px;
`;

// 使用示例
function SearchBar() {
  return (
    <SearchContainer>
      <SearchInput placeholder="搜索..." />
    </SearchContainer>
  );
}

核心逻辑:clip-path: polygon()通过定义多边形顶点坐标,直接把容器右侧切割成三角形状,input撑满容器后就呈现出目标样式。调整calc(100% - 12px)里的数值可以修改三角的宽度。

注意:方法二兼容性稍差(不支持IE),如果需要兼容旧浏览器优先选方法一;现代浏览器下方法二更简洁。

内容的提问来源于stack exchange,提问作者ZooPanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:42:08