我试图在第一次点击时使 svg 旋转,然后在第二次点击时平稳地旋转回原始位置。我有以下代码。
HTML:
<div class="quick-access">
<div class="quick-access__toggle">
<svg id="toggle-button" viewBox="0 0 100 100" >
<path d="M 50 30 L 50 70" stroke="white" stroke-width="5"/>
<path d="M 30 50 L 70 50" stroke="white" stroke-width="5"/>
</svg>
</div>
</div>
SCSS:
$colour-orange: #faab18;
.quick-access{
position: absolute;
bottom: 20px;
right: 20px;
&__toggle{
width: 50px;
height: 50px;
border-radius: 50%;
background: $colour-orange;
}
}
.open{
background: white;
svg{
transition-property: transform;
transition-duration: 0.7s;
path{
stroke: $colour-orange;
}
}
}
.overlay{
background: rgba(30,30,30,0.6);
}
JS:
$('.quick-access__toggle').on('click', function(){
$(this).toggleClass('open');
if($(this).hasClass('open')){
$('#toggle-button').css('transform', 'rotate(225deg)');
}else{
$('#toggle-button').css('transform', 'rotate(0deg)');
}
$('body').toggleClass('overlay')
})
我想要发生的是 svg 在单击时旋转到 225 度,然后在第二次单击时它旋转到 0 度。目前它旋转到 225 度,但在第二次点击时它不会像第一次点击那样平滑地旋转,它只是重置回原来的位置。我认为 transition-property 和 transition-duration 可以做到这一点,但它只适用于第一次点击。我尝试过制作 js 动画,但它不支持转换,我宁愿不使用插件或 polyfill 来完成这项工作。
最佳答案
问题是因为您只在 open
类添加到元素后才添加 transform
规则 - 而 rotate()
属性是同时添加的,所以没有动画。
要解决此问题,您需要在 .quick-access__toggle
的默认状态上定义 transform
规则。然后,您可以简单地在修改 rotate()
规则的元素上切换 CSS 类。两个状态之间的转换
会很平滑,JS代码也简洁很多。试试这个:
$('.quick-access__toggle').on('click', function() {
$(this).toggleClass('open');
$('body').toggleClass('overlay')
})
.quick-access {
position: absolute;
bottom: 20px;
right: 20px;
}
.quick-access__toggle {
width: 50px;
height: 50px;
border-radius: 50%;
background: #faab18;
}
.quick-access__toggle svg {
transition: transform 0.7s;
transform: rotate(0deg);
}
.open {
background: white;
}
.open svg {
transform: rotate(225deg);
}
.open path {
stroke: #faab18;
}
.overlay {
background: rgba(30, 30, 30, 0.6);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quick-access">
<div class="quick-access__toggle">
<svg id="toggle-button" viewBox="0 0 100 100">
<path d="M 50 30 L 50 70" stroke="white" stroke-width="5"/>
<path d="M 30 50 L 70 50" stroke="white" stroke-width="5"/>
</svg>
</div>
</div>
请注意,我必须将您的 SCSS 转换为普通的旧 CSS 才能使代码段正常工作,但转换回来应该很容易。
关于Javascript/css 转换仅在第一次工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091921/