我有一个对象生成器。它运作正常。
'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
还有另一种方式(我更喜欢一条线)吗?不幸的是, 我不擅长英语,如果有问题,题目,请编辑它们。
答案 0 :(得分:1)
在你的函数中将this.left更改为
this.left = function () {
return window.getComputedStyle(this.loc).getPropertyValue('left');
}
然后在你的通话中将其改为
console.log(d.left());
答案 1 :(得分: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'));