将交通信号灯图像转换为后续颜色错误的功能

问题描述 投票:0回答:2

我有一个图像元素和三个图像(Red.pngAmber.pngGreen.png)。我希望我的代码通过单击将图像元素更改为下一个图像。

<img src="Red.png" id="toggleImage" onclick="toggleImage()">
function toggleImage() {
    var img1 = "Red.png";
    var img2 = "Amber.png";
    var img3 = "Green.png";
    var imgElement = document.getElementById('toggleImage');
    if (imgElement.src = img1) {
        imgElement.src = img2;
    }
    if (imgElement.src = img2) {
        imgElement.src = img3;
    }
    if (imgElement.src = img3) {
        imgElement.src = img1
    }
}

[当红绿灯以Red.png开头并且我单击它时,它没有改变。

当它以Amber.png开头并单击时,它变成Red.png,并且不再更改。

当它以Green.png开头时,单击时将更改为Red.png,但再次单击不会更改任何内容。我已经尝试过将其作为其他条件,但它不起作用,而是变为Amber.png,而不是红色。

javascript html image traffic
2个回答
1
投票

使用else if,因为原来的if方法对人眼来说太快了。

function toggleImage() {
    var img1 = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Red_Circle%28small%29.svg/1024px-Red_Circle%28small%29.svg.png";
    var img2 = "https://www.publicdomainpictures.net/pictures/310000/nahled/yellow-circle.png";
    var img3 = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7a/LACMTA_Circle_Green_Line.svg/1024px-LACMTA_Circle_Green_Line.svg.png";
    var imgElement = document.getElementById('toggleImage');
  
    if (imgElement.src == img1) {
      // Red to Yellow
      imgElement.src = img2;
    }
    else if (imgElement.src == img2) {
      // Yellow to Green
      imgElement.src = img3;
    }
    else if (imgElement.src == img3) {
      // Green to Red
      imgElement.src = img1;
    }
  
    return 0;
}
<img id="toggleImage" onclick="toggleImage()" style="width: 100px; height: 100px; background: black;" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Red_Circle%28small%29.svg/1024px-Red_Circle%28small%29.svg.png">

0
投票

$('img').on({
    'click': function() {
         document.querySelector('span').textContent = $(this).attr('src');
         var src = ($(this).attr('src') === 'image-photo/red-traffic-light-city-street-600w-425010472.jpg')
             ? 'image-vector/green-traffic-light-isolated-on-260nw-1539482378.jpg'
             : 'image-photo/red-traffic-light-city-street-600w-425010472.jpg';
         $(this).attr('src', src);
     }
});
#img1 {
  cursor: pointer;
}

span {
  vertical-align: top;
  padding: 5px 10px;
  background: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<base href="https://image.shutterstock.com/">
<img id="img1" src="image-photo/red-traffic-light-city-street-600w-425010472.jpg" height="300" width="300">
<span></span>

希望这可以帮助您了解其工作原理。努力解决自己想要的任何事情。

© www.soinside.com 2019 - 2024. All rights reserved.