我试图通过按下左右键来改变汽车角度,下面的代码只改变角度一次,我需要在每次按左或右键时改变角度。任何帮助?
<!DOCTYPE html>
<html>
<head>
<style>
#myCar {
width: 60px;
height: 30px;
}
</style>
</head>
<body>
<img id="myCar" src="driver.png">
<h1>myCar</h1>
<script>
function myFunctionR() {
// Code for Chrome, Safari, Opera
document.getElementById("myCar").style.WebkitTransform = "rotate(20deg)";
// Code for IE9
document.getElementById("myCar").style.msTransform = "rotate(20deg)";
document.getElementById("myCar").style.transform = "rotate(20deg)";
}
function myFunctionL() {
// Code for Chrome, Safari, Opera
document.getElementById("myCar").style.WebkitTransform = "rotate(-20deg)";
// Code for IE9
document.getElementById("myCar").style.msTransform = "rotate(-20deg)";
document.getElementById("myCar").style.transform = "rotate(-20deg)";
}
document.onkeydown = checkKey;
function checkKey(e){
e = e || window.event;
switch(e.keyCode){
case 37: myFunctionL(); break;
case 39: myFunctionR(); break;
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
您希望添加或减去金额到已经存在的金额。我会做这样的事情:
function getAngle(el) {
// Get the transform-value from any of the possible style-elements
var transform = el.style.transform || el.style.WebkitTransform || el.style.msTransform;
// return the degrees currently there or 0 if there is non
return parseInt(transform.substring(7, transform.indexOf('deg)'))) || 0;
}
function setAngle(el, deg) {
el.style.transform = 'rotate(' + deg + 'deg)';
el.style.msTransform = 'rotate(' + deg + 'deg)';
el.style.WebkitTransform = 'rotate(' + deg + 'deg)';
}
function changeAngle(el, deg) {
setAngle(el, getAngle(el)+deg);
}
function myFunctionR() {
changeAngle(document.getElementById('myCar'), 20);
}
function myFunctionL() {
changeAngle(document.getElementById('myCar'), -20);
}
未经测试且可能有错误(可能||
不是使其在所有浏览器中都能正常工作的最佳方式)但这应该可以帮助您实现目标。