我想知道是否有一种简单的方法,在点击一个div后将其旋转90度,并在下次点击它时将其返回到0度(使div旋转-90度)。
由于我找不到任何我需要的东西,所以希望得到您的帮助。谢谢。
$('button:first-of-type').on('click', ()=> $('#rotate').toggleClass('rotated'));
const btn = document.querySelector('button:nth-of-type(2)');
const block2 = document.querySelector('#rotate2');
btn.addEventListener('click', ()=>block2.classList.toggle('rotated'));
body {text-align: center;}
#rotate, #rotate2 {
width: 100px;
height: 100px;
background: red;
border-top: 10px solid black;
transition: transform .2s ease;
margin: 20px auto;
color: #fff;
}
.rotated {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>rotate block</button>
<div id="rotate">jQuery</div>
<button>rotate block</button>
<div id="rotate2">Vanilla</div>
#rotate{ width: 100px; height: 100px; background: red; margin: 50px; text-align: center; -webkit-transition: transform 1s ease; -moz-transition: transform 1s ease; -ms-transition: transform 1s ease; -o-transition: transform 1s ease; transition: transform 1s ease; }
- prettyInPink您需要使用CSS来旋转div
。对于+ - 90
,您需要添加/删除div
以实现简单的 toggleClass
。将此行为添加到click
事件中将产生以下结果。
$('.square').click(function() {
$(this).toggleClass('rotate-90');
});
.square {
width: 150px;
height: 100px;
background-color: red;
}
.rotate-90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square">
</div>