<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
a{
color:green;
text-decoration: none; /*去除下划线*/
}
div{
height: 1000px;
border: 2px solid red;
color: blue;
}
div:target{ /*表示目标div的样式*/
background-color: #ccc;
color: rgb(255, 127, 202);
}
</style>
<body>
<a href="#abc">hello world</a>
<div>
</div>
<div id="abc">
欢迎来到新世界
</div>
</body>
</html>
上面的这个代码,当点击a标签时,页面会定位到id值为abc的这个div上面。
效果如图:
使用该锚点定位会有bug,在vue项目,不管是hash路由还是history路由,均会改变url的地址
此外 实现锚点定位的另一个方法:
使用scrollIntoView方法进行定位到某一位置
<span @click="jumpClick()">点击这</span>
//这是锚点的入口,绑定点击事件
<div id="anchor">跳到这里来</div>
//还是需要先定义锚点的目的地
jumpClick(){
document.querySelector('#anchor').scrollIntoView(true)
//如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐
//如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐
}
还可以配置参数定位的位置和动画效果:
document.querySelector('#anchor').scrollIntoView({
behavior: "smooth",
// 定义动画过渡效果, "auto"或 "smooth" 之一。默认为 "auto"
block: "center",
// 定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"
inline: "nearest"
// 定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"
})