[英]Select element and toggle class to rotate child elements independently
我感觉自己已经接近了,但现在似乎陷入僵局。 我是js / jquery n00b,所以我可能不太了解,只是不知道。
我已经得到了我单击旋转的父div的子对象(切换.rotated
类),然后,当单击另一个父div时, .rotated
类又被切换了,子div旋转了,并且从先前单击的父div的子级中删除.rotated
类。
我似乎无法弄清楚的是,如果子div的父级连续两次被单击,那么如何切换子div的.rotated
类。 如果此说明令人困惑,请参阅底部的小提琴。
我知道为什么它不起作用(当我单击一个已经旋转的div时, if
语句为true
,并且其中的代码与自身发生冲突),我只是不太了解如何使它执行操作我想要。
HTML示例 (最终产品将具有多个div)
<div class="one-fourth">
<div class="collapse-container">Collapser 1
<div class="plus-logo" id="logo_1">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" viewBox="0 0 144 144" xml:space="preserve">
<path d="M2 72.2c0-38.6 31.4-70 70-70 38.6 0 70 31.4 70 70 0 38.7-31.4 70-70 70C33.4 142.2 2 110.9 2 72.2z" fill="#244385" />
<path d="M59.1 84.5H23.8V58h35.3V22.7h26.5V58h35.3v26.4H85.6v35.3H59.1V84.5z" fill="#FFF" />
<polygon points="72 7.2 79.1 19.5 64.9 19.5 " fill="#F6D432" />
</svg>
</div>
</div>
</div>
的CSS
.one-fourth {
width: 22%;
margin: 1%;
float: left;
text-align: center;
background: lightgreen;
box-sizing: border-box;
padding: 2%;
cursor: pointer;
}
.plus-logo {
width: 32%;
-moz-transition: all 0.5s ease;
-webkit-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
margin: 10px auto;
}
.plus-logo svg {
vertical-align: middle;
}
.rotated {
-moz-transform: rotate(180deg);
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
}
JS
$('.collapse-container').click(function() {
var rotated_logo = $('.collapse-container').find('.rotated').attr('id');
if (typeof rotated_logo !== 'undefined') {
$('#'+rotated_logo).removeClass('rotated');
$(this).children().toggleClass('rotated');
} else {
$(this).children().toggleClass('rotated');
}
});
小提琴
那是您要达到的目标吗?
https://jsfiddle.net/tkfg05ta/
// store for the last rotated html element
var lastRotated;
// Define the listener on the body element instead of having
//a few listeners for each .collapse-container
$('body').on('click','.collapse-container', function(e){
// Get the '.plus-logo' child of the currently clicked element
var plusLogoNode = $('.plus-logo',this);
plusLogoNode.toggleClass('rotated');
// $('selector')[0] - gets the first element from the jquery collection
// as pure html node
// If there is last rotated element and that element is not
// the currently clicked than remove the class of lastRotated
(lastRotated && !lastRotated[0].isSameNode(plusLogoNode[0])) && (lastRotated.removeClass('rotated'));
// Now the last rotated is the current
lastRotated = plusLogoNode;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.