Javascript-改变图像的宽度

Javascript - changing widths of images

本文关键字:图像 改变 Javascript-      更新时间:2023-09-26

我正在创建一个拔河游戏网站作为一个小项目。我的问题是我的javascript似乎不想工作。

    <script>
        function randomTeam(){
            var TeamV = Math.floor((Math.random() *2 ) + 1)
            document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
            return TeamV;
        }
        function changeWidth(TeamV){
            var MetreLeftV = document.getElementById('MetreLeft');
            var MetreRightV = document.getElementById('MetreRight');
            if(TeamV == 1){
                MetreLeftV.style.width += '10px';
                MetreRightV.style.width -= '10px';
            }
            else if(TeamV == 2){
                MetreRightV.style.width += '10px';
                MetreLeftV.style.width -= '10px';
            }
        }
    </script>

基本上,当加载页面时,会调用randomTeam函数,当按下按钮时,它会增加你的团队一侧的大小,并减少敌人团队的一侧。问题是,它根本不起作用。有人能帮我看看哪里出了问题吗?提前感谢:')

不能只在宽度上加10px。将宽度转换为数字,加10,然后再加px。

MetreLeftV.style.width = (parseFloat(MetreLeftV.style.width) + 10) + "px" 

对其他人也这样做,你需要检查负数。

function randomTeam() {
  var TeamV = Math.floor((Math.random() * 2) + 1)
  document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
  return TeamV;
}
function changeWidth(TeamV) {
  var MetreLeftV = document.getElementById('MetreLeft');
  var MetreRightV = document.getElementById('MetreRight');
  console.log(parseFloat(MetreLeftV.style.width) + 10 + 'px')
  if (TeamV == 1) {
    MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) + 10 + 'px';
    MetreRightV.style.width = parseFloat(MetreRightV.style.width) - 10 + 'px';
  } else if (TeamV == 2) {
    MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) - 10 + 'px';
    MetreRightV.style.width = parseFloat(MetreRightV.style.width) + 10 + 'px'
  }
}
window.setInterval( function () {
    var move = randomTeam();
    changeWidth(move);
}, 1000);
#MetreLeft {
  background-color: red
}
#MetreRight {
  background-color: yellow
}
<div id="TeamHeader"></div>
<div id="MetreLeft" style="width:200px">Left</div>
<div id="MetreRight" style="width:200px">Right</div>