javascript - 单击时旋转图像图标

标签 javascript jquery html css

想知道是否有人可以帮助我解决这个问题。我希望能够单击文本/图标,然后在单击时,+ 图标旋转 45 度,看起来像 x 图标。第二次点击时,图标会旋转回来看起来像 + 图标,依此类推。

任何帮助将不胜感激!

JSFIDDLE

https://jsfiddle.net/d264kt2t/

HTML

<div class="container">

<div class="pointer">
CLICK ME<img src="http://www.ssglobalsupply.com/images/plus.png" class="coolImage">
</div>

</div>

CSS

.container{
  width:100%;
  padding-top:100px;
  padding-bottom:100px;
  background-color:#000;

}

.coolImage{
  height:17px;
  width:17px;
  margin-left:7px;
}

.pointer{
  cursor:pointer;
  text-align:center;
  font-size:20px;
  color:#fff;
}

最佳答案

简洁漂亮的动画

就我个人而言,我不喜欢 Louys 过于冗长和无趣的解决方案。

在这里,我们可以使用 jQuery 创建更漂亮的东西:

rotated = false;
$('.pointer').click(function(){
  elem = this;
  
  $({rotation: 225*rotated}).animate({rotation: 225*!rotated}, {
    duration: 500,
    step: function(now) {
      $(elem).css({'transform' : 'rotate('+ now +'deg)'});
    }
  });
  rotated=!rotated;
});

参见 JSFiddle或片段:

i = 1;
$('.pointer').click(function(){
  elem = $(this).children("img")[0];
  
  $({rotation: 225*!i}).animate({rotation: 225*i}, {
    duration: 500,
    step: function(now) {
      $(elem).css({'transform' : 'rotate('+ now +'deg)'});
    }
  });
  i=!i;
});
.container{
  width:100%;
  padding-top:100px;
  padding-bottom:100px;
  background-color:#000;
  text-align:center;
  font-size:20px;
  color:#fff;
}

.coolImage{
  height:17px;
  width:17px;
  margin-left:7px;
}

.pointer{
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

<div class="pointer">
CLICK ME<img src="/image/Tgf0C.png" class="coolImage">
</div>

</div>

我们jQuery#animate能够生成流畅动画的“假”对象。如果您想加快或减慢动画速度,您可以将 duration 更改为其他内容。

rotated 用作提供切换功能的替代变量。

请询问是否需要进一步说明。

关于javascript - 单击时旋转图像图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119932/

相关文章:

javascript - 对条件 div 进行 React 路由

javascript - 使用 getElementsByClassName 似乎获取了太多元素

jQUery Mobile 共享页眉和页脚

html - 为什么 flexbox 居中在 I.E 11 中不起作用?

javascript - 如何检查具有相同 id 的某些按钮值 javascript

javascript - 通知 : closable "false" not working?

javascript - Angular Electron 和 AudioWorklet.addModule() 错误 DOMException : The user aborted a request

jquery - 在具有相同类别的多个 div 上查找最接近的图像

javascript - 使用 php 从 AJAX 调用更新 DataTable

css - 如何剪切 HTML5 视频顶部和底部的黑色区域?