簡體   English   中英

如何在“樣式”標簽中使用變量?

[英]How do I use a variable in the “style” tag?

我將如何在此行中使用變量? 我的變量是“ 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中為<img>document.write()

<script>
var rand1 = Math.floor(Math.random() * 1000) + 1  
var rand2 = Math.floor(Math.random() * 1000) + 1
document.write("<img ... style='position:absolute; TOP:"+rand1+"px"+" LEFT:"+rand2+"px' ...");
</script>

或者干脆改變的值.top.left通過JavaScript。 例如:

document.getElementById("myImage").style.top = rand1;
document.getElementById("myImage").style.left = rand2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM