【问题标题】:Rotate on hover then stay in that position when clicked, return to original position when clicked again悬停时旋转然后单击时停留在该位置,再次单击时返回原始位置
【发布时间】:2013-07-16 05:58:53
【问题描述】:

我想让图像在悬停时旋转 180 度。当单击/选择图像时,我希望图像保持在该位置,直到它再次被选择时它应该返回到其原始位置。

我尝试了 CSS 的组合,它适用于悬停但不会持续存在。然后我发现了一些使用 jQuery 的帖子,但由于我发现的示例非常基本,所以我对它的理解不足以在再次选择时返回图像。

HTML

<div class="conversionFormE" id="switch1">
  <label class="swapHide">Swap?</label>
  <input type="button" class="rotate" id="switch" name="switch" value="" onclick="switchUnits()"/>
</div>

一些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(180deg);
  -moz-transform:rotate(180deg);
  -o-transform:rotate(180deg);
}

感谢您的帮助。

编辑:按要求提供 onClick 功能。

function switchUnits(){

//need to get values before swap to and from around.
var from = $("#from").val();
var to = $("#to").val();

//switches the details
$("#to #"+from).attr("selected","selected");
$("#from #"+to).attr("selected","selected");

//gets values after switch
from = $("#from").val();
to = $("#to").val();

//run convert
convertUnits();
}

编辑:非常希望实现这一点: 图像是否可以在悬停时再次旋转回其原始位置而无需单击它?所以它会是:

在 posA 中,悬停,旋转,单击,停留在 posB。 在 posB 中,悬停,向后旋转,单击,再次停留在 posA。

【问题讨论】:

  • onclick="switchUnits()" 属性指向一个 javascript 函数,您应该在问题中包含该函数的代码。

标签: javascript jquery html css


【解决方案1】:

您可以将.rotate.rotated 之类的选择器添加到您的CSS .rotate:hover。这样,当存在额外的 rotated 类时,样式也会被应用。

现在您可以添加以下 jQuery 以在单击时切换该类:

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

还有一个例子:http://jsfiddle.net/MZhG5/

【讨论】:

  • Fiddle 工作得很好,但是当我使用代码时,它仍然不会“粘住”或点击一次?
  • 你包括 jQuery 吗?您的浏览器控制台中是否出现任何错误?
  • 完全没有错误,jquery 被包括在内,但它看起来好像没有被调用?!将函数移动到包含其他函数的文件中,据我所知,它在那里不起作用,然后将它移动到主文件中,仍然没有乐趣?!
  • 您是否将它放在$(document).ready 块或类似块中,以确保 DOM 已准备好?检查代码时单击后是否添加了rotated 类?
  • oops:) 我有可能是 jquery 的新手。我把它放在 document.ready 里面,效果很好! :) 谢谢!
【解决方案2】:

试试下面的代码:

var clicked = 0;
$(".rotate").click(function () {
   clicked++;
   if (clicked == 1) {
       $(this).addClass("stay");
   }
}).bind("mouseout", function () {
    if (clicked == 2) {
        $(this).removeClass("stay").addClass('normal');
        clicked = 0;
    }
});

CSS:

.rotate:hover, .stay {
    -webkit-transform:rotate(180deg);
    -moz-transform:rotate(180deg);
    -o-transform:rotate(180deg);
}
.normal {
    -webkit-transform:rotate(0deg)!important;
    -moz-transform:rotate(0deg)!important;
    -o-transform:rotate(0deg)!important;
}

示例:http://jsfiddle.net/ScSHm/

【讨论】:

  • 嗨,点击后它不会保持原位?
  • 我的方法有点复杂。与@PeterVR 相比
  • 过于复杂:) 我是 jquery 新手,现在一切都过于复杂了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多