gpt4 book ai didi

javascript - 如何在 "style"标签中使用变量?

转载 作者:行者123 更新时间:2023-12-03 08:42:52 25 4
gpt4 key购买 nike

如何在此行中使用变量?我的变量是“rand1”和“rand2”

style="position:absolute; TOP:'rand1'px; LEFT:'rand2'px"

这是我的完整代码。

<script>
var rand1 = Math.floor(Math.random() * 1000) + 1
var rand2 = Math.floor(Math.random() * 1000) + 1
</script>

<img id="myImage"
src="redsquare.jpg"
width="100"
height="100"
style="position:absolute; TOP:'rand1'px; LEFT:'rand2'px"
onClick="alert(rand1); alert(rand2)">

我的目的是让图像在屏幕上随机位置弹出,并且可以单击,但此代码仅将红色方形图像放在左上角。

在position:absolute中,我的变量所在位置通常会有一个数字,并且不会有引号,所以它看起来像这样:

style="position:absolute; TOP:100px; LEFT:200px"

我以为我可以用变量替换数字,但这不起作用。

最佳答案

解析 css 值时不会评估脚本变量。

您可以使用脚本来更改样式值

<img id="myImage" src="redsquare.jpg" width="100" height="100" style="position:absolute;" onClick="alert(rand1); alert(rand2)" />
<script>
myImage.style.top = Math.ceil(Math.random() * 1000) + 'px';
myImage.style.top = Math.ceil(Math.random() * 1000) + 'px';
</script>

请注意,脚本是在创建元素之后放置的。

关于javascript - 如何在 "style"标签中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005894/

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