我的程序中有一张图像,希望用户每次单击都能旋转90度。因为图像是自动倾斜放置在程序中的,所以在允许用户这样做之前,我需要使用CSS旋转图像。这样,当单击它时,图像将水平和侧面出现。目前,我的HTML代码中的onClick事件似乎只能运行一次。
我尝试声明一个变量以增加每次点击的旋转值,但是这样做完全消除了旋转
<html>
<head>
<script>
var degrees = 57;
function rotateImage() {
var img = document.getElementById('c-channel');
degrees += 90;
img.style.transform = 'rotate(degrees)';
}
</script>
<style>
#c-channel{
position: absolute;
cursor:move;
width:190px;
height:150px;
transform:rotate(57deg);
}
</style>
</head>
<body>
<img id="c-channel" src="https://cdn.glitch.com/2a39b17c-6b95-46ec9d5c-cf9db18cd879%2Foutput-onlinepngtools%20(6).png?v=1564485433523" onclick="rotateImage()">
</body>
</html>
我希望程序允许用户每次单击将图像再旋转90度,但是单击图像不会产生可见的变化。
答案 0 :(得分:2)
您没有使用degrees
变量,可以按如下方式使用字符串模板:
var degrees = 57;
function rotateImage() {
var img = document.getElementById('c-channel');
degrees = (degrees % 360) + 90;
//img.style.transform = 'rotate(' + degrees + 'deg)';
img.style.transform = `rotate(${degrees}deg)`;
}
#c-channel {
position: absolute;
cursor: move;
width: 190px;
height: 150px;
transform: rotate(57deg);
border: grey;
}
<img id="c-channel" onclick="rotateImage()">
答案 1 :(得分:2)
您将度数用作字符串而不是实际值,并且还需要在其旁边附加一个单位。
var degrees = 57;
var img = document.getElementById('c-channel');
function rotateImage() {
degrees += 90;
img.style.transform = 'rotate('+degrees+'deg)';
}
#c-channel {
position: absolute;
cursor: move;
width: 190px;
height: 150px;
transform: rotate(57deg);
}
<img id="c-channel" src="https://cdn.glitch.com/2a39b17c-6b95-46ec9d5c-cf9db18cd879%2Foutput-onlinepngtools%20(6).png?v=1564485433523" onclick="rotateImage()">