在 JavaScript 中,你可以借助 ref 属性定位元素,然后使用 scrollIntoView 方法将该元素滚动到可见区域。以下分别从 Vue 3 和原生 JavaScript 两个角度为你介绍具体实现方式。
Vue 3 中使用 ref 结合 scrollIntoView
示例代码
<template>
<div>
<!-- 长列表 -->
<div v-for="i in 100" :key="i" :ref="setItemRef" style="height: 50px; border: 1px solid #ccc;">
Item {{ i }}
</div>
<!-- 点击按钮滚动到指定元素 -->
<button @click="scrollToItem(50)">Scroll to Item 50</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
// 创建一个 ref 对象来存储元素引用
const itemRefs = ref([]);
// 设置元素引用的函数
const setItemRef = (el) => {
if (el) {
itemRefs.value.push(el);
}
};
// 滚动到指定元素的函数
const scrollToItem = (index) => {
const targetElement = itemRefs.value[index - 1];
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth', // 平滑滚动
block: 'center' // 元素滚动到视口中心
});
}
};
</script>
代码解释
创建 ref 对象:借助 ref 创建 itemRefs 数组,用于存储每个列表项的引用。
设置元素引用:在 v-for 循环里使用 :ref="setItemRef" 调用 setItemRef 函数,将每个元素的引用添加到 itemRefs 数组中。
滚动到指定元素:点击按钮时调用 scrollToItem 函数,通过索引从 itemRefs 数组中获取目标元素,然后调用 scrollIntoView 方法将其滚动到可见区域。
原生 JavaScript 中使用 querySelector 结合 scrollIntoView
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll to Element</title>
<style>
.item {
height: 50px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<!-- 长列表 -->
<div id="list">
<div class="item" data-index="1">Item 1</div>
<div class="item" data-index="2">Item 2</div>
<!-- 更多列表项 -->
<div class="item" data-index="100">Item 100</div>
</div>
<!-- 点击按钮滚动到指定元素 -->
<button onclick="scrollToItem(50)">Scroll to Item 50</button>
<script>
// 滚动到指定元素的函数
function scrollToItem(index) {
// 使用 querySelector 根据 data-index 属性定位元素
const targetElement = document.querySelector(`.item[data-index="${index}"]`);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth', // 平滑滚动
block: 'center' // 元素滚动到视口中心
});
}
}
</script>
</body>
</html>
代码解释
定位元素:利用 document.querySelector 方法根据元素的 data-index 属性定位目标元素。
滚动到指定元素:若找到目标元素,调用 scrollIntoView 方法将其滚动到可见区域。
以上两种方法都能实现利用元素定位并滚动到该元素的功能,你可以根据具体的项目需求进行选择。