需求:
需要从页面A跳转到页面B的指定位置;
具体思路:
第一、需要在B页面拿到A页面要跳转的具体位置;
第二、使用jquery的animate方法传入scrollTop进行丝滑的滚动;
具体实现:
在这里自己使用的是判断当前序号02距离文档顶部的距离,然后模拟滚动到此,其实现的原理是一样的,具体代码实现如下所示:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
box-sizing: border-box;
height: 100%;
}
body {
display: flex;
flex-direction: column;
text-align: center;
}
.gd-flex {
display: flex;
}
.gd-flex-v {
display: flex;
flex-direction: column;
}
.title {
width: 100%;
line-height: 32px;
margin: 16px 0px;
font-size: 24px;
font-weight: 700;
}
.content {
flex: 1;
width: 200px;
margin: 0 auto;
border: 1px solid black;
overflow-y: auto;
}
.color-red {
color: red;
}
</style>
</head>
<body>
<div class="title">这是一个标题</div>
<div class="content">
<div class="gd-flex">
<p class="color-red">01</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">02</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">03</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">04</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">05</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">06</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">07</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">08</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
<div class="gd-flex">
<p class="color-red">09</p>
<p class="p">This is some text. This is some text. This is some text. This is some text. This is some text. This
is some text.
</p>
</div>
</div>
<script>
$(document).ready(function () {
$('.color-red').each(function (index, item) {
var text = $(item).text();
if (text == 02) {
// 获取匹配元素在当前视口的相对偏移
var scrollTop = $(item).offset().top - 150;
console.log('scrollTop', scrollTop);
$('.content').animate({
scrollTop: scrollTop
}, 500)
}
})
});
</script>
</body>
</html>