选择元素并切换类以独立旋转子元素

时间:2016-01-08 23:20:38

标签: javascript jquery html css rotation

我觉得我很亲密,但我现在似乎陷入了僵局。我是js / jquery n00b,所以我可能会离开,只是不知道。

我已经得到了我点击旋转的父div的子项(切换.rotated类),然后当单击不同的父div时, .rotated类再次切换,子div旋转,并从先前单击的父div的子项中删除.rotated类。

我似乎无法弄清楚,如果连续两次点击其父级,则如何切换.rotated子div的类。如果这种描述令人困惑,请参阅底部的小提琴。

我知道为什么它不起作用(当我点击已经旋转过的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/brentfincham/fzejx81u/16/

1 个答案:

答案 0 :(得分:0)

这是你想要实现的目标吗?

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;
});