如何根据更新的x位置值向左移动此div?

时间:2015-06-12 21:13:02

标签: javascript css position

http://codepen.io/leongaban/pen/WvOmwL

enter image description here

这应该非常简单,尝试答案found here无济于事。

d.style.left = x_pos+'px';

我有一个div #carousel-list我希望根据<而左右移动>导航按钮。

当前的javascript:

document.getElementById('move-right').addEventListener("click", moveRight, false);

var carousel = document.getElementById("carousel-list");

function getPosX(el) {
  // yay readability
  for (var lx=0;
       el != null;
       lx += el.offsetLeft, el = el.offsetParent);
  return {x: lx};
}

function moveRight() {
  var currentX = getPosX(carousel);
  console.log(currentX.x); // returns 0
  console.log(currentX - 20); // returns NaN for some reason
  carousel.style.left = (currentX - 20)+'px';
  console.log(currentX.x); // still returns 0 so div does not move
}

关于我的想法我无法移动carousel div?或者,当(currentX - 20)是数字NaN时,currentX返回0的原因是什么?

1 个答案:

答案 0 :(得分:2)

糟糕,改变:

carousel.style.left = (currentX - 20)+'px';

为:

carousel.style.left = (currentX.x - 20)+'px';