如何使用javascript使图像移动?

问题描述 投票:0回答:1

所以我有一个背景图片,但没有带标签的HTML,但我想让背景图片在某些类型的javascript上移动。但是当我将img标签添加到html中时,它涵盖了其他所有内容。这是一个现场example我不知道那么多的JavaScript,所以我卡住了。

body { background-image: url('images/bg_2880.jpg'); }

我需要javascript来移动鼠标上的图像悬停像js fiddle

javascript html css
1个回答
4
投票

这被称为视差效应

简单的例子:

addEventListener('mousemove', ev => {
  const force = 100;
  const dx = -ev.clientX / window.innerWidth * force;
  const dy = -ev.clientY / window.innerHeight * force;
  document.body.style.backgroundPositionX = dx + 'px';
  document.body.style.backgroundPositionY = dy + 'px';
});
body {
  background-image: url("http://placekitten.com/700/700");
}
#foo {
  position: fixed;
  bottom: 0;
  left: calc((100% - 200px) / 2);
}
<img src="http://placekitten.com/200/200" id="foo" />
© www.soinside.com 2019 - 2024. All rights reserved.