使用 JQuery 的 TranslateX

TranslateX using JQuery

TranslateX 在 JQuery 中对我不起作用。我想使用 .animate() 方法而不是 .css().

JavaScript

$(".test").hover(function() {
    $(this).animate({'transform': 'translateX(100%);'}, 1000);
});

CSS

.test {
  background-color: #f9333c;
  width: 100%;
  height: 100%;
  transform: translateX(0%);
}

这里是 fiddle 使用 animate。我添加了一些代码注释来引导您了解正在发生的事情。

HTML:

<h1 class="test">test</h1>

JavaScript:

//Get the element you want to animate
var testElement = $('.test');

function run(v){
  //Reverse the array
  var reversed = JSON.parse(JSON.stringify(v)).reverse();

  $(v[0]).animate(v[1], {
      //The speed the element moves - lower is faster
      duration: 500,
      step: function(val) {
          //Adding the transform to your element
          testElement.css("transform", `translateX(${val}px)`); 
      },
      done: function(){
          //Re-running the function but in reverse with the reverse we did above
          run(reversed)
      }
  })
};

//Calling our function and passing in the parameters
run([{y:0}, {y:100}])

您需要尝试使用传递给 run() 的值。

有一个 similar answer here 显示了如何使用 translateY 完成此操作,但是我发现代码乍一看有点难以掌握,所以我对其进行了一些剖析并制作了它使用 translateX 为您的场景工作。