for循环渲染图片重叠且报leftSideImages.node未定义、404错误如何解决
问题修复方案
1. 404报错修复
检查你的项目目录下是否存在image/smile.png文件,常见问题是目录名拼写错误(比如应该是images而不是image)、文件名大小写不匹配、路径层级错误,修正为正确的相对路径即可。
2. TypeError报错修复
你对DOM操作API的使用存在多处错误:
cloneNode(true)返回的本身就是克隆后的DOM节点,不需要额外访问.node属性- 不存在
theLeftSide.theRightSide这个属性,你原本的逻辑应该是克隆左侧的所有笑脸,删除多出来的那一个,再放到右侧容器,正确的操作逻辑如下:
// 克隆左侧所有节点 const leftSideImages = theLeftSide.cloneNode(true); // 删除克隆节点里的最后一个笑脸,保证右侧比左侧少一个 leftSideImages.removeChild(leftSideImages.lastChild); // 把处理后的节点全部追加到右侧容器 theRightSide.appendChild(leftSideImages);
3. 笑脸重叠问题修复
- 首先要给笑脸img设置绝对定位,不然
top和left属性不会生效,你可以给img加行内样式face.style.position = 'absolute',同时给父容器#leftSide、#rightSide设置相对定位,让笑脸的定位基于父容器 Math.random()不需要传参,你写的Math.random(1 * 400)是错误写法,正确的随机数生成逻辑是Math.floor(Math.random() * 400) + 1- 定位值需要加
px单位,不然浏览器无法识别,要改成face.style.top = randomTop + 'px'、face.style.left = randomLeft + 'px'
修复后完整可运行代码
<body onload="generateFaces()"> <h1> matching game </h1> <p>'Click on the extra smiling face on the left.'</p> <div id="leftSide" style="position: relative; width: 400px; height: 400px; float: left;"></div> <div id="rightSide" style="position: relative; width: 400px; height: 400px; float: left;"></div> <script> let numberOfFaces = 5; const theLeftSide = document.getElementById("leftSide"); const theRightSide = document.getElementById("rightSide"); function generateFaces(){ // 清空之前的内容,避免重复追加 theLeftSide.innerHTML = ''; theRightSide.innerHTML = ''; for(let i = 0; i < numberOfFaces; i++){ const face = document.createElement('img'); face.src = 'image/smile.png'; // 确认此处路径正确 face.style.position = 'absolute'; let randomTop = Math.floor(Math.random() * 400)+1; let randomLeft = Math.floor(Math.random() * 400)+ 1; face.style.top = randomTop + 'px'; face.style.left = randomLeft + 'px'; theLeftSide.appendChild(face); } const leftSideImages = theLeftSide.cloneNode(true); leftSideImages.removeChild(leftSideImages.lastChild); theRightSide.appendChild(leftSideImages); } </script> </body>
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

