jQuery 将鼠标悬停在背景图像上(单视差)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19424317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Move the background image on mouse over (Single Parallax)
提问by Simon
I would like to make the background image move slightly on the X and Y axis when the mouse is in the "landing-content" DIV, it should move with the movement of the mouse. it should move inverse. EG. Mouse move down, "landing-content" image moves up.
当鼠标位于“着陆内容”DIV 时,我想让背景图像在 X 和 Y 轴上略微移动,它应该随着鼠标的移动而移动。它应该反向移动。例如。鼠标向下移动,“登陆内容”图像向上移动。
HTML
HTML
<div id="landing-content">
<section class="slider">
<img src="http://i.imgur.com/fVWomWz.png"></img>
</section>
</div>
CSS
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;
}
JSFiddlehttp://jsfiddle.net/uMk7m/
JSFiddle http://jsfiddle.net/uMk7m/
Any help would be apprecated.
任何帮助将不胜感激。
回答by Tom Bowers
You could use the mousemove event, as shown in this fiddle. http://jsfiddle.net/X7UwG/
您可以使用 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');
});
It's just a quick example though, you'll have to play with the numbers yourself. ;)
这只是一个简单的例子,你必须自己玩数字。;)
回答by MLeFevre
You could achieve it like this
你可以这样实现
$(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');
});
});
回答by N8FURY
Check this fiddle. I think you will find what you want. http://jsfiddle.net/Aveendra/uXPkE/
检查这个小提琴。我想你会找到你想要的。 http://jsfiddle.net/Aveendra/uXPkE/
$('#landing-content').mousemove(function(e){
$(this).css('background-position',''+e.pageX/10+'px '+e.pageY/10+'px');
});