鼠标悬停时,双图像背景移动



因此,我试图实现的是构建一个HTML页面,该页面具有从鼠标向相反方向移动的背景。问题是,我想创建一个双层图像,一个背景和一个前景。前景图像较小,而背景图像为全宽图像。到目前为止,这是我的代码:

<!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>trymoving</title>
<style type="text/css">
body
{
margin:0;
padding:0;
}
section
{
height:100vh;
background:url(background-image.png);
overflow:hidden;
}
.sec2 {
width: 100%;
position: relative;
top: 0;
left: 0;
background:url('foreground-image.png');
}

</style>
</head>
<body>
<section class="first">
<div class="sec2"></div>
</section>
<script>
const section = document.getElementsByTagName('section')[0];
section.addEventListener('mousemove', (e) =>{
const moveX = (e.pageX * -1 / 40);
const moveY = (e.pageY * -1 / 40);
section.style.backgroundPosition = moveX + 'px ' + moveY + 'px';
});

const section2 = document.getElementsByClassName('sec2')[0];
section2.addEventListener('mousemove', (e) =>{
const moveX = (e.pageX * -1 / 10);
const moveY = (e.pageY * -1 / 10);
section2.style.backgroundPosition = moveX + 'px ' + moveY + 'px';
});
</script>
</body>
</html>

我目前的问题是前景图像向左对齐。我要它在在中间。此外,我想让它在多种屏幕尺寸上都能做出响应。

这需要对css、html和javascript进行一些调整。

使内部图像居中:我用display: flex将内部图像居中,因为你也尝试过。。。您将其应用于子元素,但需要在父元素上进行设置

移动前景图像:我用img元素替换了内部的section元素。在编辑backgroundPosition时背景仍然四处移动,但是需要通过JavaScript编辑topleft来移动前景图像。为此,您需要在前景图像上设置position: relative

调整事件侦听器:您只需要侦听父section元素上的mousemove事件。参见以下代码:

<head>
...
<style type="text/css">
body {
margin: 0;
padding: 0;
}
#background {
height: 100vh;
background: url(https://wallpapercave.com/wp/12oNQS9.jpg);
overflow: hidden;
background-repeat: no-repeat;
display: flex;
align-items: center;
justify-content: center;
}
#foreground {
position: relative;
}
</style>
</head>
<body>
<section id="background">
<img id="foreground" src="data:image/jpg;base64,/9j/..."></div>
</section>
<script>
const backgroundEl = document.getElementById("background");
const foregroundEl = document.getElementById("foreground");
backgroundEl.addEventListener("mousemove", (e) => {
const moveBackgroundX = (e.pageX * -1) / 40;
const moveBackgroundY = (e.pageY * -1) / 40;
const moveForegroundX = (e.pageX * -1) / 10;
const moveForegroundY = (e.pageY * -1) / 10;
backgroundEl.style.backgroundPosition = moveBackgroundX + "px " + moveBackgroundY + "px";
foregroundEl.style.left = moveForegroundX + "px ";
foregroundEl.style.top = moveForegroundY + "px ";
});
</script>
</body>

我还更新了你的codesandbox

我不确定这是否正是你想要的,但这会使背景图像居中,并将图像向相反的方向移动

const moveX = ((e.pageX) - (window.innerWidth / 2)) / 30;
const moveY = ((e.pageY)  - (window.innerHeight / 2)) / 30;
section.style.backgroundPosition = (50 - moveX + "% ") + (50 - moveY + "%");

最新更新