2015-05-09 69 views
0

我有一个对象生成器。它正常工作。如何正确更新对象?

'use strict'; 
function Div(isim) { 
    this.loc = document.getElementById(isim); 
    var style = window.getComputedStyle(this.loc); 
    this.width = style.getPropertyValue('width'); 
    this.height = style.getPropertyValue('height'); 
    this.left = style.getPropertyValue('left'); 
    this.top = style.getPropertyValue('top'); 
} 

但后来我更新的元素

var d = new Div("d"); 
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px"; 
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px"; 
console.log(d.left); //gives auto 
console.log(d.width); //gives the right value 

console.log(d.left)是错误的性质。我已经找到一种方法来解决它,但它是一个有点脏,我认为:

var d = new Div("d"); 
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px"; 
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px"; 
d = new Div("d"); 
console.log(d.left); //gives the right value 
console.log(d.width); //gives the right value 

是否有另一种方式(我更喜欢一个行)?不幸的是, 我不擅长英语,如果有问题的错误,标题,请编辑它们。

回答

1

值缓存,因此你需要重新计算。

function Div(isim) { 
    this.loc = document.getElementById(isim); 
    var style = window.getComputedStyle(this.loc); 
    this.width = style.getPropertyValue('width'); 
    this.height = style.getPropertyValue('height'); 
    this.left = style.getPropertyValue('left'); 
    this.top = style.getPropertyValue('top'); 
    this.getStyle = function (prop) { 
     return style.getPropertyValue(prop); 
    }.bind(this); 
} 

function getRandomInt(min, max) { 
    return Math.floor(Math.random() * (max - min + 1)) + min; 
} 

var d = new Div("d"); 
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px"; 
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px"; 
console.log(d.getStyle('left')); 
console.log(d.getStyle('width')); 

http://jsfiddle.net/s72vg53z/1/

1

在你的函数变化this.left到

this.left = function() { 
    return window.getComputedStyle(this.loc).getPropertyValue('left'); 
} 

然后在呼叫改变它

console.log(d.left());