jQuery addClass example

Change class name on click in jQuery

by Yin Yong

HTML

<h1>
点击按钮创建红三角,点击三角来移动
</h1>
<button>Create</button>
<div id="box">
  <div class="target"></div>
</div>

CSS

#box {
  width: 800px;
  height: 400px;
  background: #ccc;
  position: relative;
}

.target {
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 999em;
  background: cyan;
  left: 40px;
  top: 40px;
}

@-webkit-keyframes rotate {
  to {
    top: 40px;
    left: 40px;
  }
}

.star {
  position: absolute;
  border-left: 20px transparent solid;
  border-right: 20px transparent solid;
  border-bottom: 20px red solid;
}

.move {
  animation: rotate 1s;
}

JavaScript

var box = $("#box");

// handle click and add class
$('button').on("click", function() {
  const x = 100 + ((Math.random() * 500) | 0);
  const y = 100 + Math.random() * 200 | 0;

  $('<div/>')
    .attr('class', 'star')
    .css('left', x)
    .css('top', y).appendTo(box);
});

$(document).delegate('.star', 'click', (e) => {
  // console.log(e)
  e.currentTarget.classList.add('move')
});