如何根据光标上的位置使背景改变其位置

时间:2018-05-14 22:03:41

标签: javascript html css

我想创建一个使用背景的网站,该背景根据光标在网站上的位置而移动。
我发现这个网站可以直观地展示我想做的事情。 http://www.alexandrerochet.com/我只需要知道如何使这些字母移动。我稍后会用图片替换它们。

2 个答案:

答案 0 :(得分:0)

您可能想尝试使用 parallax.js 来达到预期的效果。

演示site

快速jsfiddle

var scene = document.getElementById('scene');
var parallaxInstance = new Parallax(scene);
parallaxInstance.friction(0.2, 0.2);
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}
.container {
	background-color: #F9F871;
	width: 100vw;
	height: 100vh;
}
.scene {
	top: 30%;
}
.layer {
	width: 100%;
	height: 200px;
}
.item {
	width: 50px;
	height: 50px;
	border-radius: 200px;
	background-color: red;
	position: relative;
}
.item-1 {
	background-color: #FF9671;
	left: 30%;
}
.item-2 {
	background-color: #D65DB1;
	left: 60%;
}
.item-3 {
	background-color: #FF6F91;
	left: 40%;
}
.item-4 {
	background-color: #FFC75F;
	left: 70%;
}
<div class="container">
	<div id="scene" class="scene">
	  <div data-depth="0.2" class="layer layer-1">
	  	<div class="item item-1"></div>
	  	<div class="item item-2"></div>
	  </div>
	  <div data-depth="0.6" class="layer layer-2">
	  	<div class="item item-3"></div>
	  	<div class="item item-4"></div>
	  </div>
	</div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/parallax/3.1.0/parallax.min.js"></script>

答案 1 :(得分:0)

您可以使用css properties实现这一目标。

  

基于Lea Verou的演讲

&#13;
&#13;
const root = document.documentElement;

document.addEventListener("mousemove", evt => {
  let x = evt.clientX / innerWidth;
  let y = evt.clientY / innerHeight;

  root.style.setProperty("--mouse-x", x);
  root.style.setProperty("--mouse-y", y);
});
&#13;
html {
  height: 100%
}

:root {
  --mouse-x: .5;
  --mouse-y: .5;
}

body {
  height: 100%;
  background-image: radial-gradient( at calc(var(--mouse-x) * 100%) calc(var(--mouse-y) * 100%), transparent, black);
}
&#13;
&#13;
&#13;

相关问题