当用户在图片父元素(此处为img
)上执行mousemove
时,我尝试在.carousel-img
上添加平滑移动效果,但我无法正常运行。
请你看看这个演示,让我知道我做错了什么?
$('.carousel-img').on('mousemove', function(e){
$('.carousel-img img').css({'transform-origin': ((e.pageX - $('.carousel-img img').offset().left) / $('.carousel-img img').width()) * 100 + '% ' + ((e.pageY - $('.carousel-img img').offset().top) / $('.carousel-img img').height()) * 100 +'%'});
})
html, body{height:100%; width:100%;}
.box{position: relative; height:100%; width:100%;}
.carousel-img {
position: absolute;
right:0;
bottom:0;
left: 0;
top:0;
padding:100px;
}
.carousel-img img {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img src="http://placehold.it/1920x600/fff/fff">
<div class="carousel-img">
<img src="http://placehold.it/200x150/ff0000/ff0000" >
</div>
</div>
答案 0 :(得分:0)
您正在更改transform-origin属性而不是transform属性。您想使用translate(x,y)
来定义您要查找的动作。
您还应该包含到img
选择器的转换,以便移动顺畅。我还添加了一些其他属性,这些属性在添加更复杂的动画(如translate3D类型)时可能很有用。
检查下面的更新代码段。
$('.carousel-img').on('mousemove', function(e) {
var translateX = ((e.pageX - $('.carousel-img img').offset().left) / $('.carousel-img img').width()) * 100;
var translateY = ((e.pageY - $('.carousel-img img').offset().top) / $('.carousel-img img').height()) * 100;
var translateProperty = 'translate(' + translateX + '%, ' + translateY + '%)';
$('.carousel-img img').css({
'-webkit-transform': translateProperty,
'-moz-transform': translateProperty,
'-ms-transform': translateProperty,
'-o-transform': translateProperty,
'transform': translateProperty
});
});
&#13;
html,
body {
height: 100%;
width: 100%;
}
.box {
position: relative;
height: 100%;
width: 100%;
}
.carousel-img {
position: absolute;
right: 0;
bottom: 0;
left: 0;
top: 0;
padding: 100px;
}
.carousel-img img {
position: relative;
/* Add transition */
transition: all 0.2s ease;
-webkit-transition: all 0.2s ease;
/* Default values for transition to be possible */
transform: translate3d(0, 0, 0);
-webkit-transform: translate3d(0, 0, 0);
transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img src="http://placehold.it/1920x600/fff/fff">
<div class="carousel-img">
<img src="http://placehold.it/200x150/ff0000/ff0000" >
</div>
</div>
&#13;