<template>
<div ref="scrollContainer" class="scroll-container">
<div ref="scrollContent" class="scroll-content">
</div>
</div>
</template>
<script setup lang="ts">
import { ref, markRaw, onMounted, onUnmounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
let router = useRouter();
// import projectShow from "@/components/indexCom/projectShow.vue";
const scrollContainer = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null);
let targetScrollY = 0;
let currentScrollY = 0;
let ticking = false;
const background = ref(null);
const handleScrollBg = () => {
const scrollY = window.scrollY;
if (scrollY !== 0 && background.value) {
background.value.style.backgroundPosition = `calc(50% + ${scrollY}px) calc(50% + ${scrollY}px)`;
} else if (background.value) {
background.value.style.backgroundPosition = "";
}
};
// 页面平滑过渡
const smoothScroll = () => {
if (!scrollContent.value) return; // 保护性检查,确保不为空
currentScrollY += (targetScrollY - currentScrollY) * 0.09; // 让滚动有缓动效果
scrollContent.value.style.transform = `translateY(${-currentScrollY}px)`;
if (Math.abs(targetScrollY - currentScrollY) > 0.5) {
requestAnimationFrame(smoothScroll);
} else {
ticking = false;
}
};
const handleScroll = (event: { deltaY: number }) => {
if (!scrollContent.value) return;
targetScrollY += event.deltaY;
targetScrollY = Math.max(
0,
Math.min(
targetScrollY,
scrollContent.value.scrollHeight - window.innerHeight
)
);
if (!ticking) {
requestAnimationFrame(smoothScroll);
ticking = true;
}
};
onMounted(() => {
console.log(window.addEventListener, "Component mounted"); // 调试日志
window.addEventListener("scroll", handleScrollBg);
if (scrollContainer.value) {
scrollContainer.value.addEventListener("wheel", handleScroll, {
passive: false,
});
}
});
onUnmounted(() => {
window.removeEventListener("scroll", handleScrollBg, false);
if (scrollContainer.value) {
scrollContainer.value.removeEventListener("wheel", handleScroll);
}
});
</script>
<style lang="scss" scoped>
html,
body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden; /* 禁用默认滚动 */
scroll-behavior: smooth;
}
.scroll-container {
min-height: 100vh;
// overflow-x: hidden;
// position: relative;
// background-color: #df9d9d;
}
.scroll-content {
will-change: transform;
position: absolute;
top: 0;
left: 0;
width: 100%;
}
</style>