如何旋转图像.onclick
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何旋转图像.onclick相关的知识,希望对你有一定的参考价值。
当我点击它时,我很难让我的图像旋转。
我附上了一个链接来调整我的html,CSS和JS
http://jsfiddle.net/5x9tgo07/32/
这是我的HTML
<html>
<header>
<h1 id='heading'>SELF</h1>
</header>
<hr>
<body>
<div class='introCard'>
<img id='self' src="https://image.ibb.co/djffuz/self_eye_centered.jpg"/>
</div>
</body>
</html>
这是我的CSS
header {
width: 100%;
height: 75px;
display: flex;
flex-direction:column;
align-items: center;
}
.introCard {
width: 100%;
margin-top: 35px;
margin-bottom: 25px;
border-radius: 5px;
display: flex;
flex-direction: column;
align-items: center
}
div img {
width: 35%;
}
hr {
width: 50%
}
这是我的JS
let imageToSpin = document.getElementById('self');
function spinImage() {
imageToSpin.rotate(20 * Math.PI/180);
}
imageToSpin.onclick = spinImage;
答案
rotate
不是Element
对象的方法。
旋转图像的正确方法是添加(或切换)CSS类并使用rotate()
旋转它。
使用你的例子:
JS档案
let imageToSpin = document.getElementById('self');
imageToSpin.onclick = function () {
imageToSpin.classList.toggle('rotated')
};
CSS文件
.rotated {
transform: rotate(90deg)
}
当然,在某个地方使用self
id的图像。
Here is your JSFiddle updated.
如果你需要在JS中计算deg
,那么你可以直接在onclick
函数中手动设置CSS属性。
另一答案
在你想要使用的东西周围创建一个闭包,然后像这样使用style.transform
:
let imageToSpin = document.getElementById('self');
function spinImage(imageToSpin) {
var count = 0
return function() {
count += 10;
imageToSpin.style.transform = `rotate(${count}deg)`;
}
}
imageToSpin.onclick = spinImage(imageToSpin);
另一答案
以下是您可以快速简短地设置它的方法:
var rotate_angle = 0;
<img src='blue_down_arrow.png' onclick='rotate_angle = (rotate_angle + 180) % 360; $(this).rotate(rotate_angle);' /></a>
以上是关于如何旋转图像.onclick的主要内容,如果未能解决你的问题,请参考以下文章
使用媒体播放器或声音池在片段内的 onClick 中播放声音