繁体   English   中英

在mousemove上移动背景图像

[英]moving background-image on mousemove

我试图使背景图像在mousemove上移动。 现在图像不会移动,只是保持不变。 另外,我认为脚本上有错误,但是我无法弄清楚哪一部分是错误的。

 /* 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> 

由于您没有使用背景图片,因此我认为您没有影响尝试修改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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM