Магнитное отталкивание карточек

Магнитное отталкивание карточек

В этом видео я покажу, как сделать эффект, при котором карточки слегка отталкиваются при наведении на активную, создавая красивую интерактивную анимацию

Описание
Видеоинструкция по подключению
Инструкция с копированием шаблона к себе
ID шаблона:
92064216
Создаём новую страницу на сайте
Шаг 1
Скроллим в самый низ и нажимаем кнопку «Указать ID шаблона»
Шаг 2
В графе указываем номер шаблона (он указан в начале инструкции), нажимаем кнопку «Выбрать»
Шаг 3
Пошаговая инструкция с подключением кода
Создаём Zero-блок и вешаем на него класс uc-repulsion-1, на последующие такие блоки вешаем свой порядковый номер: uc-repulsion-2, uc-repulsion-3 и тд
1 шаг
В этом же Zero-блоке создаем необходимое кол. карточек, разворачиваем их под нужным углом и перемешиваем между собой. Вешаем на каждую класс repulsion
2 шаг
Добавить код в блок T123 внизу страницы или футере
Код из видео

<!--Магнитное отталкивание карточек
https://mt-webdesign.ru/repulsion-->
<script src="https://matilda-design.ru/library/GSAP.js"></script>
<style>
.repulsion {
perspective: 2000px;
pointer-events: none;
}
.repulsion .tn-atom {
pointer-events: all !important;
}
</style>
<script>
$(document).ready(function() {
if (!window.matchMedia("(min-width: 1200px)").matches) return;
$('[class*="uc-repulsion-"]').each(function() {
const groupContainer = $(this);
const atomsInGroup = groupContainer.find('.repulsion .tn-atom');
const itemsInGroup = groupContainer.find('.repulsion');
let zIndexTimeout;
groupContainer.css('perspective', '1000px');
atomsInGroup.css('transformStyle', 'preserve-3d');
atomsInGroup.each(function() {
const atom = $(this);
const transform = atom.css('transform');
let angle = 0;
if (transform !== 'none') {
const values = transform.split('(')[1].split(')')[0].split(',');
const a = parseFloat(values[0]);
const b = parseFloat(values[1]);
angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
}
atom.data({
'orig-rotation': angle,
'orig-x': atom.position().left,
'orig-y': atom.position().top
});
});
itemsInGroup.each(function() {
const item = $(this);
item.data('orig-z', parseInt(item.css('z-index')) || 1);
});
atomsInGroup.on('mouseenter', function() {
const hoveredAtom = $(this);
const hoveredIndex = atomsInGroup.index(hoveredAtom);
const hoveredItem = hoveredAtom.closest('.repulsion');
clearTimeout(zIndexTimeout);
atomsInGroup.each(function(i) {
const currentAtom = $(this);
const currentItem = currentAtom.closest('.repulsion');
gsap.killTweensOf(currentAtom);
if (i === hoveredIndex) {
gsap.to(currentAtom, {
rotation: 0,
rotationX: 0,
rotationY: 0,
x: 0,
y: 0,
scale: 1.15, // увеличение активной карточки
duration: 1.2,
ease: 'elastic.out(0.5, 0.3)',
overwrite: "auto"
});
zIndexTimeout = setTimeout(() => {
currentItem.css('z-index', 100);
}, 200);
} else {
const directionX = i < hoveredIndex ? -1 : 1;
const directionY = (i % 2 === 0 ? -1 : 1);
const distance = Math.abs(hoveredIndex - i);
const tiltX = directionX * Math.max(3, 12 - distance * 3);
const rotateY = -directionX * Math.max(8, 35 - distance * 6); // 35 - max угол наклона по X
gsap.to(currentAtom, {
x: directionX * 140, // расстояние смещения по оси X от активной карточки
y: directionY * 30, // расстояние смещения по оси Y от активной карточки
rotationX: tiltX,
rotationY: rotateY,
rotation: currentAtom.data('orig-rotation'),
scale: 0.9, // уменьшение не активных карточек
transformOrigin: 'center center',
duration: 1.2,
ease: 'elastic.out(0.5, 0.3)',
overwrite: "auto"
});
currentItem.css('z-index', currentItem.data('orig-z'));
}
});
});
atomsInGroup.on('mouseleave', function() {
clearTimeout(zIndexTimeout);
atomsInGroup.each(function() {
const atom = $(this);
const item = atom.closest('.repulsion');
gsap.killTweensOf(atom);
gsap.to(atom, {
rotation: atom.data('orig-rotation'),
rotationX: 0,
rotationY: 0,
x: 0,
y: 0,
scale: 1,
duration: 1.2,
ease: 'elastic.out(0.5, 0.3)',
overwrite: "auto"
});
item.css('z-index', item.data('orig-z'));
});
});
});
});
</script>
Более подробные настройки, возможности взаимодействия и подключение в видео
Другие модификации
3D галерея
Tilda
Подсказки при наведении курсора
Tilda