我创建了一个视差效果,其中图像和文本的移动方向与鼠标的移动方向相反。这发生在一个叫做parallax-wrapper的元素中。但是当我移出元素时,我希望图像和文本返回到原来的位置。我试图检测元素外部的鼠标位置,但由于某种原因它没有正确触发。Javascript中的视差问题
的codepen链接 - https://codepen.io/rohitgd/pen/gRLNad?editors=1010
HTML
<div class="parallax-wrapper">
<div class="layer" data-mouse-parallax="0.1">
<img src="https://tympanus.net/Development/MorphingBackgroundShapes/img/1.jpg"/>
</div>
<div class="layer" data-mouse-parallax="0.3">REVERT</div>
</div>
CSS
body {
background-color:#fff;
padding: 100px;
display: flex;
justify-content: center;
align-items: center;
}
.parallax-wrapper {
width: 500px;
height: 300px;
background-color:#0c0c0c;
position: relative;
overflow: hidden;
.layer {
width: 80%;
height: 80%;
position: absolute;
left: 30px;
text-align: center;
line-height: 300px;
font-size: 38px;
color:#FFF;
transition: all 200ms ease-out;
}
}
img {
width: 200px;
height: 200px;
position: relative;
top: 50px;
right: 70px;
}
的Javascript
$(".parallax-wrapper").mousemove(function(e) {
var x = e.pageX - $(this).offset().left - $(this).width()/2;
var y = e.pageY - $(this).offset().top - $(this).height()/2;
$("*[data-mouse-parallax]").each(function() {
var factor = parseFloat($(this).data("mouse-parallax"));
x = -x * factor;
y = -y * factor;
$(this).css({ transform: "translate3d(" + x + "px, " + y + "px, 0)" });
});
});
$(document).mouseleave(function(e) {
var target = $(e.target);
if(!target.is("div.layer")) {
alert('out of the element');
e.stopPropagation();
}
});
当鼠标超出了我要的是视差 - 包装图像和文本返回到原来的位置。
非常感谢!这正是我正在寻找的。我做了@Archer写的背景颜色,而不是改变背景颜色。现在它工作得很好! –
很乐意帮忙。但是你的代码中有另一个bug,我认为这是因为CSS。当你将包装物放到顶部时,它不会触发事件。最有可能是定位问题,你应该使用不同的方式来通过CSS定位包装。但这是另一个问题的问题,没有视差等**等待**或者可能不是。我注意到这只发生在codepen上。在这里所以它工作正常 – pid
这绝对是一个codepen问题,测试它是否也在你的网站上! – pid