javascript - Oclick Javascript 函数不工作

标签 javascript jquery css onclick

我有一张我想旋转的图片,

<img src="images/anchor.png" alt="robot image" class="robot rotate" width="100px" height="100px" />

下面的css代码用来旋转图片

.rotate{
    -webkit-transition-duration: 0.8s;
    -moz-transition-duration: 0.8s;
    -o-transition-duration: 0.8s;
    transition-duration: 0.8s;

    -webkit-transition-property: -webkit-transform;
    -moz-transition-property: -moz-transform;
    -o-transition-property: -o-transform;
    transition-property: transform;

    overflow:hidden;
}  

.rotate:hover {
    -webkit-transform:rotate(-90deg);
    -moz-transform:rotate(-90deg);
    -o-transform:rotate(-90deg);
} 

最后是 jquery 让它在点击时发生

$(document).ready(function () {
    $('img.rotate').click(function () {
        $('img.rotate').addClass('hover');
    }, function () {
        $('img.rotate').removeClass('hover');
    });
    alert("working?");
});

但是当我点击图像时,所有发生的事情都是我的图像由于我的 css 而旋转。我想要发生的是当图像被点击时它会开始旋转,而不是当我将鼠标悬停在它上面时。

这是我的 fiddle http://jsfiddle.net/sneakmiggz/7B8Ya/

最佳答案

Demo

  • 在您的 CSS 中使用 .hover。你正在从你的 JS 添加类 .hover,css :hover 不会为它工作。
  • 尽可能使用$(this)
  • 使用 .toggleClass() 添加/删除类。

CSS:

.rotate.hover {
    -webkit-transform:rotate(-90deg);
    -moz-transform:rotate(-90deg);
    -o-transform:rotate(-90deg);
} 

JS:

$('img.rotate').click(function () {
    $(this).toggleClass('hover');
});

关于javascript - Oclick Javascript 函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24291650/

相关文章:

javascript - 光标:鼠标抓取javascript

javascript - 单击转到模态部分

javascript - Html anchor 链接和hashbang,简单的解决方案吗?

javascript - jsPDF库无法将utf8字母插入pdf

jquery - JSONP 和 jQuery 分块

css - 双无序列表中心问题。

javascript - 在音频元素中播放 Spotify 歌曲预览

javascript - 获取鼠标移动速度

html - 文字装饰 : none not working at all

html - 为什么这个 CSS 动画会导致 chrome 崩溃,我该如何解决?