Anchor
Navegação pelas seções do documento com rastreamento, recuo e histórico.
Quando usar
Âncora liga o índice às seções da página longa e mostra a seção ativa ao rolar. É adequado para documentação, condições de pedidos e artigos com identificadores de cabeçalho estáveis. Para transições entre as páginas, use Menu.
Container, Fixação e Recuo
Sem configuração, a rolagem da janela é usada. Para a área local getContainer Retorna HTMLElement; Ao contrário de Affix.target o tipo público desse getter não permite null. Dê o nó via bind:this como nos exemplos. O getter geral pode ser definido via ConfigProvider.getTargetContainer.
offsetTop Especifica a posição do PIN. targetOffset Define o recuo do alvo ao mover e definir a seção atual; O valor de um determinado item tem prioridade. bounds — Tolerância para definir a partição ativa. Com um cabeçalho fixo, defina o recuo de acordo com sua altura real: caso contrário, o título estará abaixo dele.
O afixo aceita boolean ou afixo configurações sem offsetTop, target e children. Valor false Deixa uma lista no fluxo; showInkInFixed Salva o indicador neste modo. Anexo de contêiner também mostra CSS-wrapper: scroll target não corta o nó fixo com as bordas da carta por si só.
História, design e acessibilidade
Para links de fragmentos locais, o componente altera o endereço via pushState ou replaceState. replace Pode ser definido como âncora ou item separado. target Refere-se ao link e permite que você abra um endereço normal de uma maneira diferente.
Ligue event.preventDefault() em onClick Cancela a mudança de história, mas não a rolagem interna da âncora. Portanto, os cartões de documentação podem rolar sem alterar o endereço de toda a página. Essa história não inicia a transição do fragmento nativo: para projetar a seção atual, use o estado do aplicativo, não apenas CSS :target.
Os links mantêm o tab nativo e entram. O componente não adiciona aria-current automaticamente; Se necessário, especifique a designação disponível da seção atual em sua própria composição. root, item, itemTitle e o indicador são configurados através de classNames/styles; Valores styles – CSS Strings. Padrões Gerais Fornece ConfigProvider.anchor, o preenchimento de tema é o componente Tokens de design (design tokens) âncora.
prefixCls Especifica a âncora de prefixo local completa. String vazio e undefined Use ConfigProvider.prefixCls com sufixo -anchor. As regras do item diferem: ausente prefixCls Herda o prefixo do proprietário da âncora permitido, a string vazia retorna o prefixo do provedor, o não vazio define seu próprio prefixo completo do link. As substituições de itens explícitos precisam de um CSS separado como em Exemplo de prefixo. Local Anchor.prefixCls não renomeia Affix; theme.cssVar.prefix Define o namespace das variáveis do tema separadamente.
Herança de links de prefixos locais – diferença consciente de Ant Design 6.6.8: lá items sem prefixo explícito manter o prefixo do provedor, que pode violar o design e a posição do indicador. Aqui o indicador segue o link ativo e com um item.prefixCls separado.
Exemplos
Navegação vertical
Aninhado items e realce da partição ao rolar o contêiner selecionado. A fixação está desativada para isolar o cartão.
<script lang="ts">
import { Anchor } from '@woodger/antd';
let area = $state<HTMLDivElement>();
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-basic-intro', title: "Descrição" },
{
key: 'delivery', href: '#anchor-basic-delivery', title: "Entrega",
children: [{ key: 'payment', href: '#anchor-basic-payment', title: "Pagamento" }]
}
])}
showInkInFixed
/>
<div
class="area"
bind:this={area}
role="region"
aria-label={("Seções básicas de âncora")}
tabindex="0"
>
<div id="anchor-basic-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-basic-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-basic-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
Navegação horizontal
âncora horizontal usa uma lista plana. O menu longo rola dentro de sua própria área.
<script lang="ts">
import { Anchor } from '@woodger/antd';
let area = $state<HTMLDivElement>();
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
.layout { grid-template-columns: minmax(0, 1fr); }
</style>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-horizontal-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-horizontal-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-horizontal-payment', title: "Pagamento" }
])}
direction="horizontal"
showInkInFixed
/>
<div class="area" bind:this={area} role="region" aria-label={("Seções de âncora horizontais")} tabindex="0">
<div id="anchor-horizontal-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-horizontal-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-horizontal-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
sem
affix=false Deixa a navegação no fluxo. showInkInFixed Controla o indicador; O rastreamento da seção é salvo.
<script lang="ts">
import { Anchor, Checkbox } from '@woodger/antd';
let area = $state<HTMLDivElement>();
let ink = $state(false);
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<div
class="controls"
><Checkbox
bind:checked={ink}
>{("Indicador de âncora estática")}</Checkbox></div>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-static-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-static-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-static-payment', title: "Pagamento" }
])}
showInkInFixed={ink}
/>
<div class="area" bind:this={area} role="region" aria-label={("seções âncora estática")} tabindex="0">
<div id="anchor-static-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-static-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-static-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
Manuseio
preventDefault Cancela URL Histórico. O Anchor continua a percorrer o contêiner e relata o link selecionado.
<script lang="ts">
import { Anchor } from '@woodger/antd';
let area = $state<HTMLDivElement>();
let clicked = $state('');
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={(event, link) => {
event.preventDefault();
clicked = link.href;
}}
items={([
{ key: 'intro', href: '#anchor-click-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-click-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-click-payment', title: "Pagamento" }
])}
/>
<div
class="area"
bind:this={area}
role="region"
aria-label={("Seções Clique em âncora")}
tabindex="0"
>
<div id="anchor-click-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-click-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-click-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
<output aria-label={("Pressionando âncora")}>{(clicked
|| ("Os links ainda não clicaram"))}</output>
Luz de fundo
getCurrentAnchor Especifica um link ativo, independentemente da rolagem real. A escolha da luz de fundo continua sendo o estado do exemplo.
<script lang="ts">
import { Anchor } from '@woodger/antd';
let area = $state<HTMLDivElement>();
let highlighted = $state('#anchor-highlight-intro');
let resolveHighlight = $derived.by(() => {
const href = highlighted;
return () => href;
});
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<div class="controls">
<label>{("Seção destacada ")}<select bind:value={highlighted}>
<option value="#anchor-highlight-intro">{("Descrição")}</option>
<option value="#anchor-highlight-delivery">{("Entrega")}</option>
<option value="#anchor-highlight-payment">{("Pagamento")}</option>
</select></label>
</div>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-highlight-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-highlight-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-highlight-payment', title: "Pagamento" }
])}
showInkInFixed
getCurrentAnchor={resolveHighlight}
/>
<div class="area" bind:this={area} role="region" aria-label={("Seções de destaque âncora")} tabindex="0">
<div id="anchor-highlight-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-highlight-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-highlight-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
Desvio de destino
targetOffset Deixa espaço acima da seção. Para um link, o nativo targetOffset tem precedência sobre o geral.
<script lang="ts">
import { Anchor } from '@woodger/antd';
let area = $state<HTMLDivElement>();
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-offset-intro', title: "Recuo 32px" },
{ key: 'delivery', href: '#anchor-offset-delivery', title: "Recuo 64px", targetOffset: 64 },
{ key: 'payment', href: '#anchor-offset-payment', title: "32px novamente" }
])}
showInkInFixed
targetOffset={32}
/>
<div class="area" bind:this={area} role="region" aria-label={("seções âncoras de deslocamento")} tabindex="0">
<div style="
height: 64px;
padding: 8px;
box-sizing: border-box;
">
{("Área acima Seções")}
</div>
<div id="anchor-offset-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-offset-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-offset-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
Alteração da seção ativa
onChange Reflete as transições entre as seções quando pressionado e rolando manualmente. A história é limitada a cinco eventos recentes.
<script lang="ts">
import { Anchor } from '@woodger/antd';
let area = $state<HTMLDivElement>();
let events = $state<string[]>([]);
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-change-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-change-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-change-payment', title: "Pagamento" }
])}
showInkInFixed
onChange={value => { events = [...events, value || "Iniciar"].slice(-5); }}
/>
<div class="area" bind:this={area} role="region" aria-label={("Seções Alterar âncora")} tabindex="0">
<div id="anchor-change-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-change-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-change-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
<output aria-label={("História de Seções âncoras")}>{(events.join(' → ')
|| ("não há eventos"))}</output>
Histórico de Transição
replace Altera o registro atual do histórico em vez de adicionar um novo. Este exemplo atualiza o fragmento intencionalmente na barra de endereços.
<script lang="ts">
import { Anchor, Checkbox } from '@woodger/antd';
let area = $state<HTMLDivElement>();
let replace = $state(true);
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
.layout { grid-template-columns: minmax(0, 1fr); }
</style>
<div class="controls">
<Checkbox bind:checked={replace}>
{("Substitua o registro do histórico da âncora")}
</Checkbox>
</div>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
items={([
{ key: 'intro', href: '#anchor-history-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-history-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-history-payment', title: "Pagamento" }
])}
replace={replace}
showInkInFixed
/>
<div class="area" bind:this={area} role="region" aria-label={("Seções de âncora de história")} tabindex="0">
<div id="anchor-history-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-history-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-history-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
Semantic styles
Função styles faz root, item, itemTitle e indicador. Ao mudar de direção, a função obtém os suportes atuais.
<script lang="ts">
import { Anchor, Checkbox } from '@woodger/antd';
let area = $state<HTMLDivElement>();
let horizontal = $state(false);
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
.layout { grid-template-columns: minmax(0, 1fr); }
</style>
<div class="controls">
<Checkbox bind:checked={horizontal}>
{("Âncora semântica horizontal")}
</Checkbox>
</div>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-semantic-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-semantic-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-semantic-payment', title: "Pagamento" }
])}
showInkInFixed
direction={horizontal ? 'horizontal' : 'vertical'}
classNames={{ root: 'semantic-anchor-root', itemTitle: 'semantic-anchor-title' }}
styles={({ props }) => ({
root: `
padding: 12px;
border: 1px solid var(--ant-color-primary-border);
border-radius: 8px;
`,
item: props.direction === 'horizontal'
? 'padding-inline:8px'
: 'padding-block:2px',
itemTitle: 'font-weight:600',
indicator: 'background:var(--ant-color-success)'
})}
/>
<div class="area" bind:this={area} role="region" aria-label={("seções âncora semântica")} tabindex="0">
<div id="anchor-semantic-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-semantic-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-semantic-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
Tokens de componentes
O tema local altera os recuos verticais e horizontais por meio de theme.components.Anchor.
<script lang="ts">
import { Anchor, ConfigProvider } from '@woodger/antd';
let area = $state<HTMLDivElement>();
</script>
<style>
.layout {
display: grid;
grid-template-columns: minmax(100px, 130px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<ConfigProvider theme={{
cssVar: {}, components: {
Anchor: {
linkPaddingBlock: 10,
linkPaddingInlineStart: 24
}
}
}}>
<div class="layout">
<Anchor
affix={false}
getContainer={() => area!}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-tokens-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-tokens-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-tokens-payment', title: "Pagamento" }
])}
showInkInFixed
/>
<div class="area" bind:this={area} role="region" aria-label={("Seções de Tokens Âncora")} tabindex="0">
<div id="anchor-tokens-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-tokens-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-tokens-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
</ConfigProvider>
Anexo de contêiner
affix Aceita os parâmetros Affix. Local contendo block e rootClassName Limite a navegação do mapa à área do mapa.
<script lang="ts">
import { Anchor } from '@woodger/antd';
let area = $state<HTMLDivElement>();
</script>
<style>
.frame {
transform: translate(0);
isolation: isolate;
overflow: hidden;
border-radius: 8px;
}
.area {
height: 220px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
}
.frame :global(.fixed-local-anchor) { top: 8px !important; }
.section {
min-height: 220px;
padding: 16px;
box-sizing: border-box;
}
.section:last-child { min-height: 300px; }
</style>
<div class="frame">
<div
class="area"
bind:this={area}
role="region"
aria-label={("âncora fixa")}
tabindex="0"
>
<div style="height:48px"></div>
<Anchor affix={{ rootClassName: 'fixed-local-anchor' }} offsetTop={8}
getContainer={() => area!} direction="horizontal" targetOffset={48}
onClick={event => event.preventDefault()}
items={([
{ key: 'intro', href: '#anchor-fixed-intro', title: "Iniciar" },
{ key: 'details', href: '#anchor-fixed-details', title: "Detalhes" }
])}
style="background:var(--ant-color-bg-container)"
/>
<div id="anchor-fixed-intro" class="section">{("Início do documento")}</div>
<div id="anchor-fixed-details" class="section">{("Detalhes do documento")}</div>
</div>
</div>
Anchor
Padrões gerais semânticos, substituindo o registro e recalculando o indicador após a mudança do recuo.
<script lang="ts">
import { Anchor, Checkbox, ConfigProvider } from '@woodger/antd';
let area = $state<HTMLDivElement>();
let spacious = $state(false);
const items = [
{ key: 'intro', href: '#anchor-provider-intro', title: "Descrição" },
{ key: 'delivery', href: '#anchor-provider-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-provider-payment', title: "Pagamento" }
];
</script>
<style>
.settings { margin-bottom: 24px; }
.examples {
display: grid;
gap: 20px;
}
.area {
height: 180px;
overflow: auto;
border-radius: 8px;
background: var(--ant-color-fill-quaternary);
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
}
.section:last-child { min-height: 240px; }
</style>
<div class="settings">
<Checkbox bind:checked={spacious}>
{("Aumente a âncora do preenchimento do link")}
</Checkbox>
</div>
<ConfigProvider anchor={{
class: 'provider-anchor', style: 'border-radius:8px',
classNames: { root: 'context-anchor-root' },
styles: () => ({
root: 'border-radius:4px',
item: `padding-block:${spacious ? 12 : 2}px`,
itemTitle: 'font-weight:600',
indicator: 'background:#237804'
})
}}>
<div class="examples">
<Anchor items={(items)} affix={false} showInkInFixed getContainer={() => area!}
onClick={event => event.preventDefault()} class="local-anchor" style="border-radius:16px"
classNames={{ root: 'local-anchor-root' }} styles={{ root: 'border-radius:12px' }} />
<ConfigProvider anchor={{}}>
<p>{("Registro vazio Restaura o design padrão:")}</p>
<Anchor items={(items)} affix={false} getContainer={() => area!}
onClick={event => event.preventDefault()} class="reset-anchor" />
</ConfigProvider>
<div bind:this={area} class="area" role="region" aria-label={("Seções de configuração Anchor")} tabindex="0">
<div id="anchor-provider-intro" class="section">{("Descrição do projeto")}</div>
<div id="anchor-provider-delivery" class="section">{("Entrega do projeto")}</div>
<div id="anchor-provider-payment" class="section">{("Pagamento do projeto")}</div>
</div>
</div>
</ConfigProvider>
Para dois links com o item explícito.prefixCls O design é definido separadamente por meio da classe. Alterar o prefixo salva links e a posição do indicador.
Prefixos e links
Geral e local prefixCls, herança item e prefixo vazio explícito. O indicador continua seguindo o link ativo.
<script lang="ts">
import { Anchor, Checkbox, ConfigProvider, type AnchorItem } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
let area = $state<HTMLDivElement>();
let active = $state('');
const prefix = $derived(custom ? 'suite' : 'ant');
const items: AnchorItem[] = $derived([
{ key: 'owner', href: '#anchor-prefix-owner', title: "herança" },
{
key: 'provider', href: '#anchor-prefix-provider', title: "Provedor", prefixCls: '',
class: `prefix-anchor-override ${active === '#anchor-prefix-provider' ? 'is-active' : ''}`
},
{
key: 'custom', href: '#anchor-prefix-custom', title: "Seu prefixo", prefixCls: 'item-anchor',
class: `prefix-anchor-override ${active === '#anchor-prefix-custom' ? 'is-active' : ''}`
}
]);
</script>
<style>
.example {
display: grid;
gap: 20px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.layout {
display: grid;
grid-template-columns: minmax(120px, 150px) minmax(0, 1fr);
gap: 16px;
}
.area {
height: 180px;
overflow: auto;
background: var(--ant-color-fill-quaternary);
border-radius: 8px;
}
.section {
min-height: 180px;
padding: 16px;
box-sizing: border-box;
overflow-wrap: anywhere;
}
.section:last-child { min-height: 240px; }
.layout :global(.prefix-anchor-override) { padding: 4px 0 4px 16px; }
.layout :global(.prefix-anchor-override > a) {
display: block;
color: var(--ant-color-text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.layout :global(.prefix-anchor-override.is-active > a) { color: var(--ant-color-primary); }
p { margin: 0; }
output { overflow-wrap: anywhere; }
@media (max-width: 640px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("pacote âncora de prefixo geral")}</Checkbox>
<Checkbox bind:checked={local}>{("âncora local de prefixo")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'anchor-theme' } }}>
<div class="layout">
<Anchor
items={(items)}
prefixCls={local ? 'project-anchor' : ''}
class="prefix-anchor-main"
affix={false}
showInkInFixed
replace
getContainer={() => area!}
onChange={href => { active = href; }}
/>
<div class="area" bind:this={area} role="region"
aria-label={("Seções âncoras com prefixo")} tabindex="0">
<div id="anchor-prefix-owner" class="section">
{("Referência herda o prefixo do proprietário da âncora.")}
</div>
<div id="anchor-prefix-provider" class="section">
{("Item vazio.prefixCls Seleciona o prefixo geral do provedor.")}
</div>
<div id="anchor-prefix-custom" class="section">
{("Item não vazio.prefixCls Especifica o prefixo completo.")}
</div>
</div>
</div>
</ConfigProvider>
<output
aria-label={("Anchor de prefixo")}
>{("\n Geral: ")}{prefix}{("; Classe: ")}{(local ? 'project-anchor' : prefix + '-anchor')}{("; Seção: ")}{(active || '—')}
</output>
<p>
{("Para dois links com o item explícito.prefixCls O design é definido separadamente por meio da classe. Alterar o prefixo salva links e a posição do indicador.")}
</p>
</div>
Seções do pedido
Exemplo de revisão salvo com descrição, entrega e pagamento locais.
<script lang="ts">
import { Anchor } from '@woodger/antd';
import { onMount } from 'svelte';
let navigation = $state<HTMLDivElement>();
let navigationVisible = $state(false);
onMount(() => {
if (!navigation) {
return;
}
const observer = new IntersectionObserver((
[entry]
) => { navigationVisible = entry.intersectionRatio === 1; }, { threshold: 1 });
observer.observe(navigation);
return () => observer.disconnect();
});
let container = $state<HTMLDivElement>();
let current = $state('');
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<div bind:this={navigation}>
<Anchor
affix={false}
showInkInFixed
getCurrentAnchor={navigationVisible ? undefined : () => ''}
direction="horizontal"
getContainer={() => container!}
targetOffset={8}
items={([
{ key: 'details', href: '#anchor-demo-details', title: "Descrição" },
{ key: 'delivery', href: '#anchor-demo-delivery', title: "Entrega" },
{ key: 'payment', href: '#anchor-demo-payment', title: "Pagamento" }
])}
onClick={event => event.preventDefault()}
onChange={value => { current = value; }}
/>
</div>
<div
bind:this={container}
style="
height: 180px;
overflow: auto;
margin-top: 12px;
background: var(--ant-color-fill-quaternary);
"
>
<div id="anchor-demo-details" style="
height: 180px;
padding: 16px;
box-sizing: border-box;
">
{("Descrição do pedido")}
</div>
<div id="anchor-demo-delivery" style="
height: 180px;
padding: 16px;
box-sizing: border-box;
">
{("Condições de entrega")}
</div>
<div id="anchor-demo-payment" style="
height: 220px;
padding: 16px;
box-sizing: border-box;
">
{("Métodos de pagamento")}
</div>
</div>
<output aria-label={("Âncora da Seção Atual")}>{current}</output>
API
Os exemplos são verificados com a página atual do Ant.Design e o público API instalado. As definições completas dos propriedades estão em @woodger/antd.
| Tema | Exemplo ou restrição |
|---|---|
| Basic | Lista vertical e links aninhados; Fixação separadamente. |
| Horizontal Anchor | Menu horizontal plano. |
| Static Anchor | affix=false e controle do indicador. |
| Customize the onClick event | Cancelar a mudança URL sem rolar. |
| Customize the anchor highlight | getCurrentAnchor e status de iluminação. |
| Set Anchor scroll offset | Preenchimento de alvo geral e individual. |
| Listening for anchor link change | História onChange. |
| Replace href in history | replaceState e pushState. |
| Custom semantic dom styling | Objeto classNames e função styles. |
| CSS prefix | âncora local, links herdados e item.prefixCls independentes. |
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
prefixCls | Completo local CSS Prefixo. A string vazia e undefined Use o prefixo geral do provedor. | string | ConfigProvider.prefixCls + "-anchor" |
items | Links; children Crie um aninhamento somente em vertical. items tem prioridade sobre children-snippet. | readonly AnchorItem[] | — |
direction | Direção do menu; Em horizontal aninhado children não são exibidos. | 'vertical' | 'horizontal' | vertical |
affix | Fixação em Affix; false Deixa âncora no fluxo. | boolean | Omit<AffixProps, ...> | true |
showInkInFixed | Mostra o indicador em affix=false. | boolean | false |
getContainer | Rastreamento e área de rolagem; Getter é chamado no navegador. | () => HTMLElement | Window | () => window |
offsetTop | Fixação de indentação e reserva de destino de reserva. | number | 0 |
targetOffset | Recuo de destino; targetOffset Um link separado tem prioridade. | number | offsetTop |
bounds | Tolerância para definir a partição ativa no PX. | number | 5 |
getCurrentAnchor | Substitui o link destacado; onChange Obtém o original href. | (activeLink: string) => string | — |
onClick | preventDefault proíbe a entrada URL; A âncora de rolagem é salva. | (event, { title, href }) => void | — |
onChange | Seção selecionada ao clicar ou rolar. | (href: string) => void | — |
replace | Substitui o registro do histórico; replace O item individual tem prioridade. | boolean | false |
classNames | Aulas de slots semânticos. | AnchorSlots | (info) => AnchorSlots | — |
styles | CSS Slots semânticos. | AnchorSlots | (info) => AnchorSlots | — |
nativeElement | bind:nativeElement Retorna a âncora externa div. | HTMLDivElement | — |
Opções de referência
AnchorItem Definir key, href, title, target, class, replace, targetOffset, prefixCls e children. title Aceita texto, número ou trecho.
item.prefixCls: undefined Herda o prefixo âncora permitido; A string vazia seleciona o prefixo geral do provedor com o sufixo -anchor; A string não vazia especifica o prefixo completo do link. Um item explícito substitui o que requer seu próprio CSS. Âncora de retorno de chamada semântico Obtenha o local props.prefixCls local original.
ConfigProvider.anchor
AnchorConfig: classstyleclassNamesstyles. class/style — strings; classNames/styles — Slots Objeto ou função com propriedades atuais.
As classes são dobradas. Prioridade de estilo de raiz: defaults.styles.root → defaults.style → local styles.root → local style. Os estilos locais de outros slots se sobrepõem aos padrões. A âncora aninhada substitui todo o registro, o objeto vazio redefine as configurações. Se você alterar semântica styles a posição do indicador é recalculada pelo link atual.
Semantic DOM
Anchor cria um div externo e links internos com reais href. Slots semânticos: root, item, itemTitle, indicator. styles aceita CSS strings; As funções obtêm propriedades atuais. Os padrões gerais são definidos por meio de ConfigProvider.anchor.
O teclado usa a guia Regular e entra em links. Quando horizontal o menu rola seguindo o link ativo. indicador decorativo; Um aria-current separado para um link ativo não atribui um componente.
Tokens de design
Ambos os tokens de componentes funcionam ConfigProvider theme.components.Anchor. O cartão mostra recuos locais; Cores comuns e tipografia herdam o tema da seção.
| Token | Atribuir |
|---|---|
linkPaddingBlock | Preenchimento de link vertical. |
linkPaddingInlineStart | Preenchimento de nível aninhado. |
| Token | Valor atual |
|---|---|
colorPrimary | #2f54eb |
colorSplit | rgba(5,5,5,0.06) |
colorText | rgba(0,0,0,0.88) |
fontFamily | -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji' |
fontSize | 14 |
lineHeight | 1.5714285714285714 |
lineType | solid |
lineWidth | 1 |
lineWidthBold | 2 |
motionDurationSlow | 0.3s |
paddingXXS | 4 |
FAQ
Por que os exemplos rolam o cartão e não a página inteira?
Cada getContainer Retorna uma área separada. No aplicativo, você pode sair da janela padrão ou selecionar seu próprio contêiner de rolagem.
Por que o menu fixo vai para o exterior target?
target Especifica a área de observação. O limite de desenho do nó fixo requer CSS composição; Ele é armazenado no exemplo de fixação.
Como desfazer a mudança URL?
Ligue preventDefault em onClick. Rolar e definir um link ativo continuará funcionando.
Por que o design não funciona :target?
O histórico muda programaticamente. O status da partição ativa está disponível em onChange e getCurrentAnchor.
É possível fazer uma lista horizontal aninhada?
horizontal Não emitir children. Para hierarquia, use vertical.