Skip to content

Skeleton 骨架屏 ​

用接近真实内容的占位形状表示加载中的页面,减少内容跳动和等待感。

何时使用 ​

  • 首次加载或切换内容时,已知内容的大致结构但数据尚未返回。
  • 卡片、文章、用户资料等需要保持布局高度的区域。
  • 只需要一个旋转指示时用 Spin;数据为空时用 Empty。

在线体验 ​

Skeleton 骨架屏 · 在线体验真实 Go 组件
在独立页面打开 ↗

查看此场景的 Go 源码 ↗

基本用法 ​

go
import "github.com/tangoui/tango/ui"

func skeletonPage(c *ui.Context) {
    ui.Skeleton(c).Rows(3).Active().Show()
}

Active() 开启 shimmer 动画,Rows(n) 设置段落行数。Show() 构建占位内容。

常见用法 ​

头像、标题和段落 ​

go
func skeletonProfile(c *ui.Context) {
    ui.Skeleton(c).Avatar(false).Rows(3).Round().Show()
}

Avatar(false) 添加圆形头像,传入 true 使用方形头像;Round() 让条带使用胶囊形状。

加载完成后切换真实内容 ​

go
var profileLoading = true

func skeletonLoading(c *ui.Context) {
    ui.Skeleton(c).Loading(profileLoading).Body(func() {
        ui.Text(c, "用户资料已加载")
    })
}

Loading(true) 显示骨架,Loading(false) 构建 Body 中的真实内容。把加载状态放在页面级变量或 ui.State,不要在渲染函数中重置。

控件占位 ​

go
func skeletonControls(c *ui.Context) {
    ui.SkeletonButton(c, ui.Middle, "default", true)
    ui.SkeletonButton(c, ui.Middle, "round", true)
    ui.SkeletonInput(c, ui.Middle, true)
    ui.SkeletonAvatar(c, 32, false, true)
    ui.SkeletonImage(c, 96, 96, false)
}

四个专用构造函数分别提供按钮、输入框、头像和图片形状;active 控制动画,尺寸使用 ui.Small、ui.Middle 或 ui.Large。

隐藏标题和段落 ​

go
func skeletonMinimal(c *ui.Context) {
    ui.Skeleton(c).NoTitle().Rows(0).Show()
}

NoTitle() 隐藏标题条,Rows(0) 隐藏段落条,适合只需要局部占位的场景。

主题与样式 ​

Skeleton 的条带高度、圆角、动画颜色和间距由主题控制。ConfigProvider.Defaults("Skeleton", ...) 支持 active 与 round 布尔默认值;单个实例的 Active、Round 优先。大量同时动画会增加绘制开销,应按可见区域拆分骨架。

注意事项 ​

骨架形状应尽量匹配最终内容,避免加载完成后大幅跳动。加载状态来自真实请求状态;不要用固定延时伪造完成。动画应避免覆盖错误和空状态,必要时提供可读的加载说明或配合 A11y 文案。大列表优先使用虚拟化或只渲染视口附近的骨架。

示例代码 ​

以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。

Skeleton 骨架屏

gallery 演示 Skeleton 的 Render 函数,源码 page_data_misc.go#L91。

加载中…

Button 按钮

gallery 演示 Button 的 Render 函数,源码 page_general.go#L15。

加载中…

Input 输入框

gallery 演示 Input 的 Render 函数,源码 page_form.go#L58。

加载中…

Image 图片

gallery 演示 Image 的具名 Render 函数,源码 page_data_image.go#L61。

加载中…

Button 图标位置与加载

gallery 演示 ButtonAlign 的 Render 函数,源码 page_b1a.go#L28。

加载中…

ButtonGroup 按钮组

gallery 演示 ButtonGroup 的 Render 函数,源码 page_button_group.go#L67。

加载中…

Button / 选择控件状态

gallery 演示 ShadButtonStates 的 Render 函数,源码 page_shad2a_entry.go#L91。

加载中…

Input 字数统计、外观变体与自定义底色

gallery 演示 InputVariants 的 Render 函数,源码 page_p2d_entry.go#L123。

加载中…

Skeleton 默认行数与宽度

gallery 演示 SkeletonAlign 的 Render 函数,源码 page_b2g.go#L122。

加载中…

Image 图片预览

gallery 演示 ImagePreview 的 Render 函数,源码 page_data_image.go#L99。

加载中…

Image 预览:缩放范围、到头即停与计数

gallery 演示 ImageAlign 的 Render 函数,源码 page_b2h.go#L121。

加载中…

API ​

签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。

入口函数 ​

ui.Skeleton ​

go
func Skeleton(c *Context) *SkeletonW

Skeleton starts a skeleton with a title and paragraph rows: three rows, or two next to an avatar or without a title (antd).

ConfigProvider.Defaults("Skeleton", ...) keys: "active", "round" (bool).

返回 *SkeletonW,可链式调用的方法见 SkeletonW 方法。

ui.SkeletonAvatar ​

go
func SkeletonAvatar(c *Context, size float32, square, active bool)

SkeletonAvatar adds an avatar placeholder.

ui.Button ​

go
func Button(c *Context, label string) *ButtonW

Button adds a button.

返回 *ButtonW,可链式调用的方法见 ButtonW 方法。

ui.Input ​

go
func Input(c *Context, val *string) *InputW

Input adds a text input bound to *val.

返回 *InputW,可链式调用的方法见 InputW 方法。

ui.Image ​

go
func Image(c *Context, img image.Image) *ImageW

Image adds an image; img may be nil (shows the placeholder). The default size is the image's pixel size (200×200 when unknown); use Width/Height.

返回 *ImageW,可链式调用的方法见 ImageW 方法。

SkeletonW 方法 ​

ui.SkeletonW:SkeletonW is a loading placeholder: optional avatar, a title bar and paragraph lines, with an optional shimmer ("active").

方法说明签名
ActiveActive turns on the shimmer animation.Active() *SkeletonW
AvatarAvatar adds a round avatar placeholder (square=true for square).Avatar(square bool) *SkeletonW
AvatarSizeAvatarSize sets the avatar placeholder size in px (antd avatar.size; default the large control height, 40).AvatarSize(px float32) *SkeletonW
BodyBody builds the skeleton while loading, else fn.Body(fn func()) *Box
CountCount repeats the skeleton n times (Element count).Count(n int) *SkeletonW
LoadingLoading switches between the skeleton (true) and the real content.Loading(on bool) *SkeletonW
NoTitleNoTitle hides the title bar.NoTitle() *SkeletonW
ParagraphWidthParagraphWidth sets the paragraph line widths (antd paragraph.width): one value sets the last line, several set the lines in order; fractions when 0 < w <= 1, else px.ParagraphWidth(w ...float32) *SkeletonW
RoundRound uses pill-shaped bars.Round() *SkeletonW
RowsRows sets the paragraph rows (0 hides the paragraph).Rows(n int) *SkeletonW
ShowShow builds the skeleton.Show() *Box
ThrottleThrottle delays the switch (EP throttle): the skeleton appears only after Loading(true) lasted leading and goes away only after Loading(false) lasted trailing (0: at once), so quick loads do not flash.Throttle(leading, trailing time.Duration) *SkeletonW
ThrottleInitialThrottleInitial sets what a throttled skeleton shows before its first delay ends: true the skeleton, false (default) the content (EP throttle.initVal).ThrottleInitial(on bool) *SkeletonW
TitleWidthTitleWidth sets the title bar width (antd title.width): a fraction of the row when 0 < w <= 1, else px.TitleWidth(w float32) *SkeletonW

ButtonW 方法 ​

ui.ButtonW:ButtonW is a button under construction; chain modifiers then query.

方法说明签名
A11yLabelA11yLabel sets the accessible name read by screen readers.A11yLabel(s string) *ButtonW
AppearanceAppearance sets how the button wears its color (Ant v6 variant, plus Element's plain).Appearance(a ButtonAppearance) *ButtonW
AutoInsertSpaceAutoInsertSpace sets whether a label of exactly two Chinese characters is drawn with a space between them ("确定" shows as "确 定"; Ant / Element ConfigProvider button.autoInsertSpace).AutoInsertSpace(on bool) *ButtonW
BlockBlock stretches the button to the container width.Block() *ButtonW
CircleCircle makes an icon-only round button.Circle() *ButtonW
ClickedClicked reports activation (never when disabled or loading).Clicked() bool
ColorColor sets the button color (Ant v6 color): a role, an Ant preset or a hex color ("#13c2c2").Color(col ButtonColor) *ButtonW
DangerDanger() *ButtonW
DashedDashed() *ButtonW
DisabledDisabled disables the button when on.Disabled(on bool) *ButtonW
GhostGhost() *ButtonW
HoveredHovered reports hover.Hovered() bool
IDID returns the widget ID.ID() ID
IconIcon puts an icon before the label.Icon(ic *icon.Icon) *ButtonW
IconPlacementIconPlacement places the icon at the inline "start" of the label (default) or at its "end" (Ant v6 iconPlacement, which replaces iconPosition).IconPlacement(p string) *ButtonW
IconRightIconRight puts the icon after the label (Icon(ic).IconPlacement("end")).IconRight(ic *icon.Icon) *ButtonW
InfoInfo makes a solid info button (Element type="info").Info() *ButtonW
LargeLarge() *ButtonW
LayoutLayout applies layout options.Layout(opts ...layout.Option) *ButtonW
LinkLink() *ButtonW
LoadingLoading shows a spinner and blocks clicks.Loading(on bool) *ButtonW
LoadingDelayLoadingDelay postpones the loading state (Ant loading.delay): after Loading(true) the button stays clickable and shows no spinner until d has passed; a loading that ends sooner never shows.LoadingDelay(d time.Duration) *ButtonW
LoadingIconLoadingIcon replaces the loading spinner with ic, drawn spinning (Ant loading.icon, Element loading-icon).LoadingIcon(ic *icon.Icon) *ButtonW
PlainPlain uses Element's plain style: a light tint of the color with a tinted border, filled with the color under the pointer.Plain() *ButtonW
PrimaryPrimary() *ButtonW
RoundRound() *ButtonW
SecondarySecondary makes a neutral filled button (shadcn "secondary").Secondary() *ButtonW
SizeSize sets the control size.Size(s ControlSize) *ButtonW
SmallSmall() *ButtonW
SuccessSuccess makes a solid success button (Element type="success"); add Plain for the plain style.Success() *ButtonW
TextText() *ButtonW
VariantVariant sets the variant explicitly.Variant(v ButtonVariant) *ButtonW
WarningWarning makes a solid warning button (Element type="warning").Warning() *ButtonW

InputW 方法 ​

ui.InputW:InputW is a single-line text input.

方法说明签名
A11yLabelA11yLabel sets the accessible name.A11yLabel(s string) *InputW
AllowClearAllowClear shows a clear button when the input has a value.AllowClear() *InputW
BgBg replaces the background color of the frame (a grey search field on a white bar).Bg(col theme.Color) *InputW
BorderlessBorderless drops the frame (background, border and focus halo), for inputs embedded in another surface such as the Command search row.Borderless() *InputW
ChangedChanged reports whether the value was edited this frame.Changed() bool
DisabledDisabled disables editing.Disabled(on bool) *InputW
EnterKeyEnterKey labels the soft keyboard's return key (input.EnterSearch, input.EnterNext, …).EnterKey(k input.EnterKey) *InputW
FocusFocus requests keyboard focus.Focus() *InputW
FocusedFocused reports keyboard focus.Focused() bool
IDID returns the editor's widget ID.ID() ID
KindKind tells soft keyboards what the field holds (input.TextEmail, input.TextNumber, …): the keyboard layout and whether it suggests words.Kind(k input.TextKind) *InputW
LayoutLayout applies layout options to the outer frame.Layout(opts ...layout.Option) *InputW
MaxLengthMaxLength limits the number of runes.MaxLength(n int) *InputW
NoBorderNoBorder drops the border and the focus halo but keeps the background (Bg or the variant's), e.g. a filled search bar.NoBorder() *InputW
PasswordPassword masks the value and adds a visibility toggle.Password() *InputW
PlaceholderPlaceholder(s string) *InputW
PrefixPrefix(ic *icon.Icon) *InputW
PrefixTextPrefixText / SuffixText show short static text (units, currency).PrefixText(s string) *InputW
ReadOnlyReadOnly prevents edits but allows selection.ReadOnly() *InputW
SelectAllSelectAll selects the full text of the input.SelectAll() *InputW
ShowCountShowCount shows the character count ("3 / 20" with MaxLength) at the end of the field (Ant showCount, Element show-word-limit).ShowCount() *InputW
SizeSize sets the control size.Size(s ControlSize) *InputW
StatusStatus sets the validation status: "error" or "warning".Status(s string) *InputW
SubmittedSubmitted reports an Enter key press.Submitted() bool
SuffixSuffix(ic *icon.Icon) *InputW
SuffixTextSuffixText(s string) *InputW
VariantVariant sets the look of the frame (Ant Input variant): "outlined" (default), "filled" (grey fill, border on focus), "borderless" (no frame) or "underlined" (bottom line only).Variant(v string) *InputW
VisibilityToggleVisibilityToggle shows (true, the default) or hides the eye button of a Password field (antd Input.Password visibilityToggle; Element type="password" without show-password).VisibilityToggle(on bool) *InputW
WidthWidth fixes the width.Width(px float32) *InputW

ImageW 方法 ​

ui.ImageW:ImageW displays a bitmap with loading placeholder, error fallback and an optional full-screen preview (Ant Design Image / Element Plus el-image).

方法说明签名
A11yLabelA11yLabel sets the accessible name (like Alt, without changing the Driver.Find label).A11yLabel(s string) *ImageW
AltAlt sets the accessible label (also used by Driver.Find).Alt(s string) *ImageW
CloseOnEscapeCloseOnEscape(false) keeps the preview open on Escape (Element close-on-press-escape, default true).CloseOnEscape(on bool) *ImageW
FailedFailed shows the error fallback (broken picture / "加载失败").Failed(on bool) *ImageW
FallbackFallback sets the image shown when loading failed (Ant `fallback`).Fallback(img image.Image) *ImageW
FitFit sets object-fit: "fill" (default), "contain", "cover", "scale-down".Fit(f string) *ImageW
HeightHeight(px float32) *ImageW
IDID returns the widget ID.ID() ID
InfiniteInfinite sets whether the group preview wraps from the last image to the first (Element infinite, default true; Ant stops at the ends).Infinite(on bool) *ImageW
LayoutLayout applies layout options.Layout(o ...layout.Option) *ImageW
LoadingLoading shows the placeholder instead of the image.Loading(on bool) *ImageW
MaskClosableMaskClosable sets whether a click on the preview backdrop closes it (Ant mask.closable, default true; Element hide-on-click-modal, default false; the theme picks the default).MaskClosable(on bool) *ImageW
MaxScaleMaxScale(k float32) *ImageW
MinScaleMinScale and MaxScale bound the preview zoom (Ant minScale 1 / maxScale 50; Element min-scale 0.2 / max-scale 7; the theme picks the default).MinScale(k float32) *ImageW
MovableMovable(false) stops dragging the preview image around (Ant preview.movable, default true).Movable(on bool) *ImageW
OpenPreviewOpenPreview opens the preview now (Ant preview.open); call it once per action, like Rotate.OpenPreview() *ImageW
PreviewPreview enables click-to-preview.Preview(on bool) *ImageW
PreviewAnglePreviewAngle returns the preview rotation in degrees (clockwise).PreviewAngle() float64
PreviewGroupPreviewGroup previews imgs (this image is imgs[index]) with prev/next navigation and a counter.PreviewGroup(imgs []image.Image, index int) *ImageW
PreviewOpenPreviewOpen reports whether the preview overlay is open.PreviewOpen() bool
PreviewScalePreviewScale returns the preview zoom factor (1 = fitted size).PreviewScale() float32
PreviewSrcPreviewSrc shows img in the preview instead of the image itself (Ant preview.src: a larger original behind a thumbnail).PreviewSrc(img image.Image) *ImageW
RadiusRadius rounds the corners.Radius(px float32) *ImageW
RotateRotate turns the open preview by deg degrees (clockwise, any angle; relative to its current rotation).Rotate(deg float64) *ImageW
ScaleStepScaleStep sets the zoom step of the preview buttons: each step scales by 1+step (Ant scaleStep 0.5; Element zoom-rate 1.2 = step 0.2).ScaleStep(step float32) *ImageW
ShowProgressShowProgress shows the "2 / 5" counter of a group preview (Ant always, Element show-progress, default false; the theme picks the default).ShowProgress(on bool) *ImageW
SizeSize fixes both sides.Size(wpx, hpx float32) *ImageW
WidthWidth / Height fix the box size in px (the other side follows the image aspect ratio when only one is set).Width(px float32) *ImageW

相关链接 ​

以 MIT 许可发布