Vue.js的鼠标悬停视差效果



大家好!我想在我的vue项目中像这个视频中那样做鼠标悬停效果。我尝试了一些代码,但属性transform只改变了一次。如果有人知道,请帮助我。codesandbox。输入输出的代码。我只是复制了我的代码的一部分不能工作。

var app = new Vue({
el: '#app',
data: {},
methods: {
parallax(e) {
document.querySelectorAll(".layer").forEach((layer) => {
const speed = layer.getAttribute("data-speed") || 2;
const x = (window.innerWidth - e.pageX * speed) / 10;
const y = (window.innerHeight - e.pageY * speed) / 10;
layer.style.transform = `translateX(${x}px) translateY(${y}px)`;
});
},
},
})
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.log {
position: relative;
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
h2 {
font-size: 3em;
}
.layer {
position: absolute;
}
.layer-1 {
top: 0;
left: 2%;
}
.layer-2 {
top: 20%;
left: 10%;
}
.layer-3 {
top: 40%;
right: 2%;
}
.layer-4 {
top: 5%;
right: 2%;
}
.layer-5 {
top: 60%;
right: 25%;
}
.layer-6 {
top: 5%;
right: 40%;
}
.layer-7 {
top: 70%;
left: 2%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="log" @mousemove="parallax">
<img
class="layer layer-1"
src="./assets/bg-1.png"
alt="bg-1"
width="5%"
data-speed="2"
/>
<img
class="layer layer-2"
src="./assets/bg-2.png"
alt="bg-2"
width="10%"
data-speed="2"
/>
<img
class="layer layer-3"
src="./assets/bg-1.png"
alt="bg-1"
width="15%"
data-speed="2"
/>
<img
class="layer layer-4"
src="./assets/bg-2.png"
alt="bg-2"
width="10%"
data-speed="2"
/>
<img
class="layer layer-5"
src="./assets/bg-1.png"
alt="bg-1"
width="25%"
data-speed="2"
/>
<img
class="layer layer-6"
src="./assets/bg-2.png"
alt="bg-2"
width="17%"
data-speed="2"
/>
<img
class="layer layer-7"
src="./assets/bg-1.png"
alt="bg-1"
width="17%"
data-speed="2"
/>
<h2>Parallax</h2>
</div>
</div>

//codesandbox.io/s/flamboyant-rosalind-u0nwx ?文件=/src/App.vue

我认为最好使用npm库的名称vue-kinesis

但是如果你想使用你的变体,你需要改变第57行:

const speed = layer.getAttribute('data-speed') || 2;

因为在每一层你没有一个属性data-speedconst speed将等于null

因此,更改我为回退编写的行,并(如果您想配置速度)在每个元素属性上添加速度data-speed="2"

相关内容

  • 没有找到相关文章

最新更新