JavaScript:点击时旋转 img



我正在尝试使用 onclick 事件处理程序使带有 id 图像的 img 旋转,以使用我的函数中的代码,该代码通过 ID 获取图像分配变量名称,然后使用变量名称旋转。我真的不确定我的代码出错了。

   <section id="middle">
    <img id="image" src="images/flower.png" >   
    <button onclick="myFunction()">Click me</button>
    </section>
MyFunction(){
var img = document.getElementById("image");
img.rotate(20*Math.PI/180);
}

您可以使用 CSS 自行执行旋转:

.rotated-image {
  -webkit-transform: rotate(20deg);
          transform: rotate(20deg);
}

在 html 上:

<section id="middle">
    <img id="image" src="images/flower.png" >   
    <button onclick="myFunction()">Click me</button>
</section>

然后,在javascript上,只需添加类:

function myFunction() {
  var img = document.getElementById("image");
  img.setAttribute("class", "rotated-image");
}

查看结果:http://jsbin.com/ibEmUFI/2/edit

尝试使用带有 id 的div 作为选择器:

<div id='image'><img src="images/flower.png" /></div>
 and 
var img = document.getElementById("image").getElementsByTagName('img');

值得一试!

我们可以使用rotate来旋转。

rotate CSS 属性允许您单独指定旋转转换,并且独立于转换属性。这样可以更好地映射到典型的用户界面用法,并且不必记住要在 transform 属性中指定的转换函数的确切顺序。

多核

const rotate = () => {
  document.querySelector("p").classList.add("rotate160deg");
}
.rotate160deg {
  rotate: 160deg;
}
// demo related stuff:
div {
  width: 150px;
  margin: 0 auto;
}
p {
  padding: 10px 5px;
  border: 3px solid black;
  width: 150px;
  font-size: 1.2rem;
  text-align: center;
}
.rotate {
  transition: rotate 1s;
}
You can do the rotation itself using CSS:
<button onclick="rotate()">rotate</button>
<div>
  <p class="rotate">😀</p>
</div>

我们使用classList将类添加到类列表中。

最新更新