我需要按顺序显示3张动物图片“猫”、“狗”和“ Frog ”。 每当用户单击“猫”图片时,就会出现一个警告窗口,提示“不要单击我, 点击 Frog ”。 每当用户单击“狗”图片时,就会出现一个警告窗口,提示“不要单击我, 点击 Frog ”。 每当用户点击“ Frog ”图片时, Frog 就会跳过猫和狗。它的意思是 一开始它显示猫狗 Frog ,当用户单击 Frog 时,它就变成 Frog 猫狗,用户再次点击 Frog 则变成猫狗 Frog 等。
编辑:图片需要是水平的,但我目前是垂直的。我似乎不知道如何使它们水平。 到目前为止,这是我的代码:
function swapDiv(event,elem){
elem.parentNode.insertBefore(elem,elem.parentNode.firstChild);
}
<div id="container">
<td><div onclick="swapDiv(event,this);"><img src="cat.png"
style="width:200;height:200;"/></div></td>
<td><div onclick="swapDiv(event,this);"><img src="dog.png"
style="width:175;height:175;"/></div></td>
<td><div onclick="swapDiv(event,this);"><img src="frog.png"
style="width:150;height:150;"/></div></td>
</div>
最佳答案
要在单行中显示图像,您需要为 #container
div 中的 div
设置 display
为 inline
在你的 CSS 中,如下所示:
#container > div {
display: inline;
}
接下来,由于您的图像需要在未单击 Frog 时显示警报,因此您可以添加一个单独的函数来创建警报
弹出窗口。然后,你可以设置猫和狗的onclick
来执行这个功能。
要使 Frog 从左向右跳,您可以在 JavaScript 中创建一个全局变量。在下面的示例中,我将其称为“frogJumped”。该变量跟踪 Frog 是否跳跃。最初,它是false
,因为 Frog 还没有跳。然后,在 swapDiv
方法中,您可以使用 if
语句检查 Frog 是否已跳跃。如果 Frog 跳了,您需要将 div 移到父级的 lastNode
之后。如果 Frog 没有跳,您需要将其移动到 container
div 的 firstChild
中。最后,您可以使用 frogJumped = !frogJumped
将 bool 值设置为与当前值相反的值。这样您每次单击 Frog 时都可以更新 Frog 的跳跃状态。
参见下面的示例:
let frogJumped = false; // Keep track of the side the frog is on
function clickFrog() { // Create a function to execute when a non-frog image is clicked
alert("Don't click me, click the frog"); // create the alert window
}
function swapDiv(event, elem) {
if(frogJumped) { // Check if the frog has jumped, if it has, move it back to its original position
elem.parentNode.insertBefore(elem, elem.parentNode.lastChild);
} else { // If the frog hasn't jumped, move it to the left of all the images
elem.parentNode.insertBefore(elem, elem.parentNode.firstChild);
}
frogJumped = !frogJumped; // Set true -> false, and false -> true
}
#container > div {
display: inline;
}
<div id="container">
<td>
<div onclick="clickFrog();"><img src="https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" style="width:200px;height:200px;" /></div>
</td>
<td>
<div onclick="clickFrog();"><img src="https://images.unsplash.com/photo-1518020382113-a7e8fc38eac9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" style="width:175px;height:175px;" /></div>
</td>
<td>
<div onclick="swapDiv(event,this);"><img src="https://images.unsplash.com/photo-1506506447188-78e2a1051d9e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" style="width:150px;height:150px;" /></div>
</td>
</div>
关于javascript - 在 JavaScript 中单击时如何旋转单个图像的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932599/