gpt4 book ai didi

Javascript 创建具有动态属性的对象

转载 作者:行者123 更新时间:2023-11-28 08:21:13 25 4
gpt4 key购买 nike

    <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又来了?

最佳答案

你可以这样做:

  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

*第一次删除答案时误读了您的问题

关于Javascript 创建具有动态属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22935123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com