我正在创建一个拔河网站作为一个小项目。我的问题是我的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函数,当按下按钮时,它会增加团队一侧的大小,并减少敌人团队的一面。问题是,它根本不起作用。任何人都可以帮我看看这出错了吗?提前谢谢你:')
答案 0 :(得分:1)
您不能只为宽度添加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);
&#13;
#MetreLeft {
background-color: red
}
#MetreRight {
background-color: yellow
}
&#13;
<div id="TeamHeader"></div>
<div id="MetreLeft" style="width:200px">Left</div>
<div id="MetreRight" style="width:200px">Right</div>
&#13;