简体   繁体   English

单击按钮时如何使图像旋转

[英]How to make a image rotate when i click the button

My html我的 html

<div id="yabanner">
  <img src="img/ok.jpg">
</div>
<button>Click Me</button>

My javascript我的 javascript

 var button = document.getElementsByTagName('button')[0];
 var image = document.getElementsByTagName('img')[0];

  button.addEventListener('click', slid , false);

  function slid(e) {
    image.src="img/kok.jpg";
    image.style.display="block";

  }

}

Can someone help me how to finish this.有人可以帮我完成这个。 I want to make a img rotate when u click the button.I tried other method(style.transform) but doesn't work:(当您单击按钮时,我想使 img 旋转。我尝试了其他方法(style.transform)但不起作用:(

You can use transform as follows:您可以按如下方式使用transform

image.style.transform = 'rotate(180deg)';

PS: you have some syntax mistakes. PS:你有一些语法错误。 The complete program would be:完整的程序将是:

<div id="yabanner">
     <img src="img/ok.jpg">
</div>
<button>Click Me</button>
<script>
var button = document.getElementsByTagName('button')[0];
var image = document.getElementsByTagName('img')[0];
button.addEventListener('click', slid , false);
function slid(e) {
      image.src="img/kok.jpg";
      image.style.display="block";
      image.style.transform = 'rotate(180deg)'; //add this
}
</script>

The html: html:

<div id="yabanner">
  <img id="rotateMe" src="https://images.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>
<button id="rotateButton">Click Me</button>

The code:编码:

console.log('rotate');
function rotateMe() {
  console.log('rotating');
  var element = document.getElementById('rotateMe');
  element.classList.add("rotateMe");
}

document.getElementById("rotateButton").addEventListener("click", rotateMe);

On css you can add all animations that you need on the rotateMe class:在 css 上,您可以在rotateMe class 上添加您需要的所有动画:

.rotateMe {
  transition: all 0.8s ease;
  transform: rotate(90deg);
}

A working example: https://stackblitz.com/edit/js-rotate-onclick?file=index.js一个工作示例: https://stackblitz.com/edit/js-rotate-onclick?file=index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM