[英]onClick event fails to perform function
我的程序中有一张图像,希望用户每次单击都可以旋转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度,但是单击图像不会产生可见变化。
您没有使用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()">
您将度数用作字符串而不是实际值,并且还需要在其旁边附加一个单位。
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()">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.