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

如何使用CSS和jQuery实现带三角形的自定义展开动效?

问题1:绘制仅顶部带边框的三角形

推荐使用clip-path方案,相比传统border实现的三角形,更容易控制单边边框样式,代码示例:

.top-border-triangle {
  /* 自定义尺寸 */
  width: 120px;
  height: 60px;
  /* 仅顶部添加边框 */
  border-top: 2px solid #222;
  /* 裁剪为等腰三角形 */
  clip-path: polygon(50% 0, 100% 100%, 0 100%);
  /* 三角形填充色 */
  background: #e64340;
}

如果需要兼容更低版本浏览器,也可以用双层border三角形错位叠加实现:做一个尺寸大1px的边框色三角形作为底层,上层放填充色三角形,向下偏移1px,仅露出顶部的边框部分即可。

问题2:实现从中心点向上下同时展开的动画

核心是控制transform-origin为元素中心,结合scaleY变换实现,动画逻辑如下:

  1. 初始状态设置transform: scaleY(0),元素高度被压缩为0
  2. 设置transform-origin: center,指定变换的基准点为元素中心
  3. 触发展开时设置transform: scaleY(1),配合过渡效果即可实现从中心向上下展开的效果
    代码示例:
.expand-element {
  transform-origin: center;
  transform: scaleY(0);
  /* 自定义动画时长和缓动效果 */
  transition: transform 0.35s ease-out;
}
/* 展开状态的类,可通过hover或JS动态添加 */
.expand-element.is-open {
  transform: scaleY(1);
}
完整整合示例

以下是同时满足两个需求的可运行代码:

<!DOCTYPE html>
<html>
<head>
<style>
.animated-shape {
  width: 240px;
  margin: 150px auto;
  /* 展开动画配置 */
  transform-origin: center;
  transform: scaleY(0);
  transition: transform 0.4s ease-out;
}
/* 顶部带边框的三角形 */
.shape-triangle {
  height: 70px;
  background: #409eff;
  border-top: 2px solid #333;
  clip-path: polygon(50% 0, 100% 100%, 0 100%);
}
/* 下方内容容器 */
.shape-content {
  height: 220px;
  background: #409eff;
  margin-top: -1px; /* 消除三角形和内容区的缝隙 */
  border-radius: 0 0 8px 8px;
}
/* 展开状态 */
.animated-shape.is-open {
  transform: scaleY(1);
}
</style>
</head>
<body>
<div class="animated-shape" id="shape">
  <div class="shape-triangle"></div>
  <div class="shape-content"></div>
</div>

<script>
// 页面加载500ms后自动触发展开
setTimeout(() => {
  document.querySelector('#shape').classList.add('is-open')
}, 500)
</script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:15:04