2017-06-10 3 views
0

なぜ私のコードがどういうわけか分かりませんでした。 `Forループが動作していないため、クローンを作成していません。

var numberOfFaces = 5; 
 
    var theleftside = document.getElementById ("leftSide"); 
 
    var top_position = Math.floor((Math.random() * 400) + 1); 
 
    var left_position = Math.floor((Math.random() * 400) + 1); 
 
    var theRightSide = document.getElementById("rightSide"); 
 

 
    function generatefaces() { 
 
     for (var i = 1; i < numberOfFaces; i++) { 
 
     var img = document.createElement("img"); 
 
     img.src = "smile.png"; 
 
     img.style.top = top_position + "px"; 
 
     img.style.left = left_position + "px"; 
 
     theleftside.appendChild(img); 
 

 
     } 
 
    }
<style media="screen"> 
 
    img { 
 
     position: absolute; 
 
    } 
 
    div { 
 
     position: absolute; 
 
     width: 500px; 
 
     height: 500px; 
 
    } 
 
    #rightSide { 
 
     left: 500px; 
 
     border-left: 2px solid black; 
 
    } 
 
    </style>
<h1>The Matching Game</h1> 
 
    <p>Click on the extra smiling face on the left.</p> 
 
    <div id="leftSide"> 
 
    </div> 
 
    <div id="rightSide"> 
 
    </div>

私はその後、右側にそれをクローン化しようとすると、異なる位置でlefside divの上5枚の画像(スマイリーフェイス)を生成しようとしています

`

私はJSで新しいので、ヒントやヒントが高く評価されます。

答えて

0

あなたは関数を実装したばかりですが、関数を呼び出さなかったためです。追加してみてください。

generatefaces(); 

最後にお試しください。

0

最初に2倍にすると、burkayのように、関数generatefaces()を呼び出す必要があります。

第2に、img.cloneNode(true)を使用して右側の2番目の要素を作成する必要があります。これにより複製が作成され、右側に追加することができます。

imgで同じランダムな位置が使用されるように、ループの外側でランダムな位置を生成している場合は、imgごとにランダムな位置を作成してループ内で移動する必要があります。

例:

var numberOfFaces = 5; 
 
var theleftside = document.getElementById("leftSide"); 
 

 
var theRightSide = document.getElementById("rightSide"); 
 

 
// You need to call this function 
 
generatefaces() 
 

 
function generatefaces() { 
 
    for (var i = 1; i < numberOfFaces; i++) { 
 
    // Generate the new random position for each img 
 
    var top_position = Math.floor((Math.random() * 400) + 1); 
 
    var left_position = Math.floor((Math.random() * 400) + 1); 
 
    var img = document.createElement("img"); 
 
    // The location of your face image 
 
    img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Emojione_1F60E.svg/64px-Emojione_1F60E.svg.png"; 
 
    img.style.top = top_position + "px"; 
 
    img.style.left = left_position + "px"; 
 
    // Creates a duplicate version of the image 
 
    var imgright = img.cloneNode(true); 
 
    theleftside.appendChild(img); 
 
    // Appends the duplicate image to the right side 
 
    theRightSide.appendChild(imgright); 
 
    } 
 
}
img { 
 
    position: absolute; 
 
} 
 

 
div { 
 
    position: absolute; 
 
    width: 500px; 
 
    height: 500px; 
 
} 
 

 
#rightSide { 
 
    left: 500px; 
 
    border-left: 2px solid black; 
 
}
<h1>The Matching Game</h1> 
 
<p>Click on the extra smiling face on the left.</p> 
 
<div id="leftSide"> 
 
</div> 
 
<div id="rightSide"> 
 
</div>

・ホープ、このことができます!

関連する問題