我的程序中有一个图像,我希望用户能够在每次单击时旋转 90 度。因为图像以倾斜 Angular 自动放置在我的程序中,所以我需要在允许用户这样做之前使用 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()">
关于javascript - onClick 事件无法执行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271997/