← 中文资源

简体中文版本

累积布局偏移(CLS)

CLS 聚合页面生命周期内可见内容的每次意外移动,按受影响面积与位移距离计分;用户主动输入引发的移动不计入。

阅读英文原文

概念定义

当可见内容在无用户输入的情况下移动时记一次偏移:视口占比乘以最大距离比。CLS 求和并使用会话窗口,让一次糟糕的爆发主导报告而非无限累积。用户面对的伤害是按钮移动导致的误点。

工作机制

布局不稳定性 API 上报每次偏移及涉事元素与距离;离散输入后短窗口内的偏移归为意图驱动而排除。开发工具的归因面板会高亮确切节点,并常能点名负责的图片、字体或脚本。

使用场景

用户会与可能移动的内容交互的一切场景:阅读流、表单、电商列表。做法是为媒体声明尺寸、让字体回退度量匹配、给异步区块与最终尺寸一致的骨架几何。

常见误区

占位符与内容尺寸不匹配会偏移两次:先缩占位、再撑内容;首屏上方的动态插入是头号惯犯。服务端中途注入横幅造成的偏移没有任何客户端技巧能掩盖——必须回到模板层修复。输入后 500ms 内的移动被视作有意,不计入。

代码示例

public class StringBuilderManipulation {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(64);

        sb.append("Hello");
        sb.append(" ");
        sb.append("World");
        System.out.println("Built: " + sb);

        sb.insert(5, " Java");
        System.out.println("After insert: " + sb);

        sb.delete(5, 10);
        System.out.println("After delete: " + sb);

        sb.replace(0, 5, "Hi");
        System.out.println("After replace: " + sb);

        sb.reverse();
        System.out.println("Reversed: " + sb);

        String csv = String.join(", ",
            "Apple", "Banana", "Cherry", "Date");
        System.out.println("CSV: " + csv);

        String formatted = String.format(
            "Name: %s, Age: %d, Score: %.2f",
            "Alice", 30, 95.5
        );
        System.out.println(formatted);

        String stripped = "  padded  ".strip();
        System.out.println("Stripped: '" + stripped + "'");
    }
}