How to swap two Div using animation
P粉191323236
P粉191323236 2023-08-26 13:55:33
0
1
299
<p>I have a project where I want a div to appear as a large box and three other divs to appear below as small boxes and when you click on a small box it will change size using a css transition effect and align with the big box Swap positions to smooth movement and size changes. Currently I'm trying to use jQuery but the positioning doesn't work at all. Here's my current example: </p> <p>https://jsfiddle.net/v3pmhawj/1/</p> <pre class="brush:php;toolbar:false;">$(function () { let { left: x1, top: y1 } = $('.full-size-card').offset() $('.inactive-sheets .card').on('click', function() { let { left: x2, top: y2 } = $(this).offset() let curr = $('.full-size-card') let diffX = x2 - x1 let diffY = y2 - y1 $(this).css({ left: -diffX, top: -diffY }) $(this).addClass('full-size-card') curr.css({ left: diffX, top: diffY }) curr.removeClass('full-size-card') }) })</pre> <p>If anyone has suggestions involving other libraries or other technologies, I'm willing to listen. I want to be able to move the divs around in the DOM, but as far as I know if you do that you can't do a css transition effect on them because the only way (that I know of) is to remove and re-add a copy of the element in the DOM. </p>
P粉191323236
P粉191323236

reply all(1)
P粉571233520

You can create animation effects simply by using transition effects. To achieve this, you need to define the width and height of the container, as well as the top and left position of the bottom element.

On click, you simply swap the class of the element that will become smaller and the class of the element that will become larger.

This is a fiddle link with an example: https://jsfiddle.net/fkd3ybwx/210/

HTML

A
B
C
D

CSS

.card-container {
  position: relative;
}

.card {
  transition: all ease 1s;
  position: absolute;
  font-size: 24px;
  border: white 4px solid;
  box-sizing: border-box;
  cursor: pointer;
}

.small {
  width: 100px;
  height: 100px;
  background: blue;
  left: 0;
  top: 300px;
}

.small ~ .small {
  left: 100px;
  background: green;
}

.small ~ .small ~ .small {
  left: 200px;
  background: yellow;
}

.large {
  width: 300px;
  height: 300px;
  background: red;
  left: 0px;
  top: 0px;
}

JavaScript

const smallCards = document.querySelectorAll('.card');

smallCards.forEach((smallCard) => {
    smallCard.addEventListener('click', (event) => {
    const largeCard = document.querySelector('.large');
    
    largeCard.className = "card small";
    event.target.className = "card large";
  });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!