通过每次点击增加一个数字来进行动态翻译

时间:2019-04-30 14:47:38

标签: javascript jquery translate3d

嗨,所以我试图在滑块中模拟箭头,在其中将元素左右移动。

到目前为止,我的项目向右移动,但是只有一次。

https://i.gyazo.com/34a0ef4a5064c2942aca7c717a775e8b.mp4

到目前为止,这是我的代码

<script>
  (function(){
    const arrowLeft = document.querySelector('#video-tags-left');
    const arrowRight = document.querySelector('#video-tags-right');
    const tags = document.querySelector('.video-tags');
    const now = "740";

    arrowRight.addEventListener("click", function() {
      $(tags).css({
        "transform": "translate3d(" + -now + "px, 0px, 0px)",
        "transform-style": "preserve-3d"
       });
    });

    arrowLeft.addEventListener("click", function() {
      $(tags).css({
        "transform": "translate3d("+ +now+", 0px, 0px)",
        "transform-style": "preserve-3d"
       });
    });
}());
</script>

因此,我尝试添加和删除now(单击时为740),因此,每次单击鼠标右键时添加740,单击鼠标左键时删除,直到重置为0px。

因此,我再次右击740,再次单击1460,等等,而当用户单击左箭头时则相反。

2 个答案:

答案 0 :(得分:0)

每次单击其中一个箭头时,都应递增/递减now的值:

<script>
    (function(){
        const arrowLeft = document.querySelector('#video-tags-left');
        const arrowRight = document.querySelector('#video-tags-right');
        const tags = document.querySelector('.video-tags');
        const SLIDER_WIDTH = 740;
        let now = 0;

        arrowRight.addEventListener("click", function() {
            now -= SLIDER_WIDTH;
            $(tags).css({
                "transform": "translate3d(" + now + "px, 0px, 0px)",
                "transform-style": "preserve-3d"
            });
        });

        arrowLeft.addEventListener("click", function() {
            now += SLIDER_WIDTH;
            $(tags).css({
                "transform": "translate3d("+ now + "px, 0px, 0px)",
                "transform-style": "preserve-3d"
            });
        });
    }());
</script>

请注意,您还必须检查滑块的限制,以便不能将滑块移到没有内容的部分。

答案 1 :(得分:0)

您的代码有一些问题:

  1. 您将“ now”声明为const,因此其值无法更改
  2. 您将“ now”声明为字符串类型,因此无法对其进行任何数学运算(例如递增或递减)

将代码更改为此:

<script>
  (function(){
    const arrowLeft = document.querySelector('#video-tags-left');
    const arrowRight = document.querySelector('#video-tags-right');
    const tags = document.querySelector('.video-tags');
    let now = 740; // Declare "now" as variable of type number

    arrowRight.addEventListener("click", function() {
      now += 740; // Increment "now" by 740
      $(tags).css({
        "transform": "translate3d(" + now + "px, 0px, 0px)",
        "transform-style": "preserve-3d"
       });
    });

    arrowLeft.addEventListener("click", function() {
      now -= 740; // Decrement "now" by 740
      $(tags).css({
        "transform": "translate3d(" + now + "px, 0px, 0px)",
        "transform-style": "preserve-3d"
       });
    });
}());
</script>