无法更新返回的element.style.left,为什么?

时间:2016-02-02 21:43:21

标签: javascript html5

我返回一个元素左侧位置,并希望稍后在循环内更改它但它不起作用。我在分配错误中得到了无效的左侧。

老实说,我不明白。如果我通过函数返回样式,它只能更新px,那么为什么会这样呢?我无法想到任何理由,因为对我来说这是完全合理的。

function pos(index) {
    return wrapper.children[index].style.left;
}

for (var i = 0; i < 10; i++) {
  wrapper.appendChild(document.createElement('div'));
  pos(i) = Math.random() * w + 'px';;
}

3 个答案:

答案 0 :(得分:3)

您没有返回指向左侧的指针,而是返回值。

您需要将值发送到pos或返回样式。

function pos(index, px) {
    wrapper.children[index].style.left = px;
}

for (var i = 0; i < 10; i++) {
    wrapper.appendChild(document.createElement('div'));
    pos(i, Math.random() * w + 'px');
}

function pos(index) {
    wrapper.children[index].style;
}

for (var i = 0; i < 10; i++) {
    wrapper.appendChild(document.createElement('div'));
    pos(i).left = Math.random() * w + 'px';
}

答案 1 :(得分:0)

尝试这样的事情:

int StackInit(struct Stack *stack) {
    stack->currentItemIndex = -1;
    stack->initialized = true;
    return SUCCESS;
}

您的函数返回您想要的对象,但您无法修改它(它不是l值)。您必须先将其存储在变量中(这是一个l值)。

答案 2 :(得分:0)

也许这就是你所需要的:

&#13;
&#13;
var newElement,
  i,
  wrapper = document.getElementById('wrapper');

for (i = 0; i < 10; i++) {
  //add the element to the wrapper
  wrapper.appendChild(getPositionedElement());

}

function getPositionedElement(){
  //Width, I don't know where you want to get this from
  var w = 1000,
      //create a new element
      el = document.createElement('div');
  //set the left position property
  el.style.left = Math.random() * w + 'px';
  return el;
}
&#13;
#wrapper {
  position: relative;
  height: 300px;
  
}

#wrapper div {
  height: 50px;
  width: 50px;
  border: 2px solid black;
  position: absolute;
}
&#13;
<div id="wrapper"></div>
&#13;
&#13;
&#13;