<body>
<div id="player" style="position: absolute; left: 30px;">Hello</div>
<script>
function Player (element) {
this.element = element;
this.left = element.style.left;
}
var player = new Player(document.querySelector('#player'));
console.log(player.left);
</script>
</body>
我有一些上面的东西。如果我调用console.log(player.left)。它归还给我30px
。然后我更改左侧属性(在开发工具中)。我仍然得到30px
。问题是,当我更改该元素时,left property of Player class
是否可以动态更改值?或者我必须再次分配值player.left = document.querySelector("#player").style.left
?
答案 0 :(得分:0)
你可以这样做:
function Player(element)
{
this.element = element;
this.left = function ()
{
return this.element.style.left
};
}
var player = new Player(document.querySelector('#player'));
console.log(player.left()); //30px
setTimeout(function () //test
{
document.querySelector('#player').style.left='100px'
console.log(player.left()); //100px
}, 2000)
http://jsbin.com/dilihofi/4/edit
*在第一次删除的答案时错过了您的问题