我试图让背景图像在鼠标移动时移动。现在图像不会移动,只是保持不变。另外,我认为脚本有错误,但我无法弄清哪个部分是错误的。
/* background movement by mouse*/
$(document).ready(function() {
var movementStrength = 25;
var height = movementStrength / $(window).height();
var width = movementStrength / $(window).width();
$("#top-image").mousemove(function(e) {
var pageX = e.pageX - ($(window).width() / 2);
var pageY = e.pageY - ($(window).height() / 2);
var newvalueX = width * pageX * -1 - 25;
var newvalueY = height * pageY * -1 - 50;
$('#top-image').css("background-position", newvalueX + "px " + newvalueY + "px");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<img id="top-image" src="https://static.pexels.com/photos/4164/landscape-mountains-nature-mountain.jpeg">
</div>
&#13;
答案 0 :(得分:1)
由于您没有使用背景图像,我认为您不会影响任何尝试修改background-position属性的内容。另外,我会将移动量基于图像尺寸,而不是窗口尺寸。试试这个:
$(document).ready(function() {
var movementStrength = 25;
var img = document.getElementById('top-image');
var imagewidth = img.clientWidth;
var imageheight = img.clientHeight;
var height = movementStrength / imageheight;
var width = movementStrength / imagewidth;
$("#top-image").mousemove(function(e) {
var pageX = e.pageX - ($(window).width() / 2);
var pageY = e.pageY - ($(window).height() / 2);
var newvalueX = width * pageX * -1;
var newvalueY = height * pageY * -1;
$(this).css("margin-left", newvalueX + "px");
$(this).css("margin-top", newvalueY + "px");
});
});
#top-image {
width: 500px;
height: auto;
padding-top:20px;
}
.container {
width: 600px;
height: 380px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
TITLE
</div>
<div class="container">
<img id="top-image" src="https://static.pexels.com/photos/4164/landscape-mountains-nature-mountain.jpeg">
</div>
<div>
Some More Text
</div>