为什么在Javascript生成的HTML img中,图像以绝对位置和随机左上角条件显示在同一位置
我对这个代码有意见为什么在Javascript生成的HTML img中,图像以绝对位置和随机左上角条件显示在同一位置,javascript,html,css,Javascript,Html,Css,我对这个代码有意见 function createSmileys(){ var i = 1; var bL=false; while(!bL){ createNode(); if(i==5){ bL=true; } i+
function createSmileys(){
var i = 1;
var bL=false;
while(!bL){
createNode();
if(i==5){
bL=true;
}
i+=1;
}
}
function createNode() {
var x_axis = Math.floor(Math.random() * 400);
var y_axis = Math.floor(Math.random() * 400);
var ls = document.getElementById("leftside");
var x = document.createElement("IMG");
x.setAttribute(":position","absolute");
x.setAttribute("float","left");
x.setAttribute("left",x_axis + "px");
x.setAttribute("top",y_axis + "px");
x.setAttribute("src", "smile.png");
x.setAttribute("width", "100px");
ls.appendChild(x);
}
虽然它创造了笑脸,但它们都在左上角对齐。
HTML代码如下:
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<script src="generateImage.js"></script>
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftside" onclick="createSmileys()"><p id="p">Left</p>
</div>
<div id="rightSide"><p id="p">Right</p></div>
</body>
配对游戏
点击左边额外的笑脸
左侧
对
请在此代码中提供帮助…请检查您的setAttribute(“:position”)
:position不是任何类型的属性。请更正它。您的style.css中有什么?检查这把小提琴:
top
,position
等都是CSS属性,而不是HTML属性setAttribute
设置HTML属性,而不是CSS属性。您需要更改元素的style
poperty(x.style.top=…;x.style.float=…
)或使用整个字符串设置其style
属性(x.setAttribute('style',position:…;'float:…;top:…
)谢谢,我把setAttribute和CSS属性搞混了,现在我已经用你提到的解决了。