将鼠标移到背景图像上(单视差)

时间:2013-10-17 10:33:15

标签: jquery html html5 css3 parallax

当鼠标位于“着陆内容”DIV中时,我想让背景图像在X和Y轴上略微移动,它应该随着鼠标的移动而移动。 它应该反向移动。例如。鼠标向下移动,“着陆内容”图像向上移动。

HTML

<div id="landing-content">
<section class="slider"> 
<img src="http://i.imgur.com/fVWomWz.png"></img>
</section>
</div>

CSS

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

.slider {
margin-left: auto;
margin-right: auto;
overflow: hidden;
padding-top: 200px;
max-width: 1002px;
}

.slider img {
width: 80%;
padding-left: 10%;
padding-right: 10%;
height: auto;
margin-left: auto;
margin-right: auto;
}

的jsfiddle http://jsfiddle.net/uMk7m/

任何帮助都会得到赞赏。

3 个答案:

答案 0 :(得分:26)

您可以使用mousemove事件,如此小提琴所示。 http://jsfiddle.net/X7UwG/

$('#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');
});

这只是一个简单的例子,你必须自己玩这些数字。 ;)

答案 1 :(得分:5)

你可以像这样实现它

$(document).ready(function(){
  $('#landing-content').mousemove(function(e){
    var x = -(e.pageX + this.offsetLeft) / 20;
    var y = -(e.pageY + this.offsetTop) / 20;
    $(this).css('background-position', x + 'px ' + y + 'px');
  });    
});

http://jsfiddle.net/uMk7m/2/

答案 2 :(得分:2)

检查这个小提琴。我想你会找到你想要的东西。 http://jsfiddle.net/Aveendra/uXPkE/

$('#landing-content').mousemove(function(e){
    $(this).css('background-position',''+e.pageX/10+'px '+e.pageY/10+'px');
});
相关问题