Multiple Transforms on mousemove jquery

2019-05-23 06:15发布

Probably an easy fix, but for the life of me I can't figure it out or may be overthinking it. In short I have a div that rotatesY based on mousemove. I have that working, but I also need it to translate across the X axis as well. So I know I have to use transform: translateX(value), but not sure how to apply two transforms the best way in jquery. Thanks for the help. Fiddle link below.

Also is there a way to change the rotationY directions?

var $window = $(window),
    $box = $('#box')
    rotation = 0;

$window.on('mousemove', function(event){    
    rotation = (event.pageX/$window.width()*90) - 45;
    $box.css('transform', 'perspective( 600px ) rotateY(' + rotation + 'deg)');
});
#box{
    width: 300px;
    height: 300px;
    margin: 30px auto;
    background: #aaa;
}
<div id="box"></div>

http://jsfiddle.net/6gbhfxrx/

1条回答
何必那么认真
2楼-- · 2019-05-23 06:46

Just apply it at the same time:

var $window = $(window),
    $box = $('#box');

$window.on('mousemove', function(event){    
    var rotation = (event.pageX/$window.width()*90) - 45;
    var transX= (event.pageX/$window.width()*500) - 250;
    $box.css('transform', 'perspective( 600px ) rotateY(' + rotation + 'deg) translateX(' + transX + 'px)');
});

Here's a fiddle: http://jsfiddle.net/6gbhfxrx/2/

查看更多
登录 后发表回答