11

当鼠标在“着陆内容”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/

任何帮助将不胜感激。

4

3 回答 3

27

您可以使用 mousemove 事件,如this fiddle所示。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');
});

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

于 2013-10-17T10:45:24.460 回答
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/

于 2013-10-17T10:46:55.773 回答
2

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

$('#landing-content').mousemove(function(e){
    $(this).css('background-position',''+e.pageX/10+'px '+e.pageY/10+'px');
});
于 2013-10-17T10:59:01.243 回答