本文介绍了跟随鼠标位置的平滑移动效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个非常简单的效果,即在鼠标移动时移动背景图像.为此,我记录了鼠标位置并使用它来修改css属性:

I want to create a very simple effect moving a background image when the mouse moves. For that Im recording the mouse position and using it to modify a css property:

$('#landing-content').mousemove(function(e){
    var amountMovedX = (e.pageX * -1 / 6);
    var amountMovedY = (e.pageY * -1 / 6);
    $(this).css('background-position', amountMovedX + 'px ' + amountMovedY + 'px');
});

http://jsfiddle.net/X7UwG/580/

我想让背景运动不那么有侵略性,起初我很好,但是只需增加等式中的分频因子即可降低较大的鼠标位置:

I want to make the background movements less aggressive, at first i though well, lets just increase the divider factor in the equation in order to make larger mouse positions lower:

http://jsfiddle.net/X7UwG/581/

此方法的主要问题是背景的移动速度确实较慢,但非常不稳定(缓慢移动鼠标).由于我们现在除以100而不是6,因此结果的非小数部分会在移动几个像素后发生变化(打开控制台并查看结果).由于背景位置仅将非十进制值作为正确值,因此移动不流畅.

The main problem with this approach is that the background is indeed moving slower BUT also very choppy (move the mouse slowly). Since we are now dividing by 100 instead of 6, the non decimal part of the result change after several pixels of movement (open console and see the result). Since background position only takes non decimal values as correct, the movement is not fluid.

我想我有两种解决方法,可以平滑移动之间的过渡,或者可以使用其他方程式将鼠标位置转换为背景差分位置,但是我不知道该如何解决.

I guess I have two ways of solving this, smoothing the transitions between the movements or have a different equation that transforms mouse position into background diferential position, but i cant figure out how to fix it.

问题的第二部分是防止背景运动超过背景大小:

The second part of the problem is to prevent the background movement to surpass the background size:

推荐答案

这样对您有用吗?

我只是将除数减小了一半,并增加了背景图像的大小以说明运动,然后将margin:0应用于身体以隐藏小提琴中存在的空白

I simply reduced the divisor by half and increased the size of the background image to account for the movement and applied margin:0 on the body to hide the whitespace that was present in the fiddle

http://jsfiddle.net/X7UwG/582/

$('#landing-content').mousemove(function(e){
    var amountMovedX = (e.pageX * -1 / 50);
    var amountMovedY = (e.pageY * -1 / 50);
    $(this).css('background-position', amountMovedX + 'px ' + amountMovedY + 'px');
    console.log(amountMovedX);
});



body {
  margin:0px;
}
#landing-content {
  overflow: hidden;
  background-image: url(http://i.imgur.com/F2FPRMd.jpg);
  width: 100%;
  background-size: 115%;
  background-repeat: no-repeat;
  max-height: 500px;
  border-bottom: solid;
  border-bottom-color: #628027;
  border-bottom-width: 5px;
  padding:0px;
}

这篇关于跟随鼠标位置的平滑移动效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:24