Поменять местами ширину и высоту (анимация)
Добрый день, уважаемые, подскажите как написать код что б у дивов за определенное время (по порядку) значение ширины становились значениями их высоты и наоборот, значения высот становились значениями ширины.
*ПС размеры каждого дива разные. Небольшой набросок <!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #field { position: relative; width: 600px; height: 600px; border: 1px solid black; background-color: red; } #bigBlock { position: relative; width: 500px; height: 500px; border: 1px solid black; margin-top: 5%; margin-left: 5%; /*background: url("snowboarder-400x385.png") 50% 50% no-repeat;*/ } .block { position: absolute; border: 3px solid white; -webkit-box-shadow: -10px 17px 25px 11px rgba(0, 0, 0, 0.6); -moz-box-shadow: -10px 17px 25px 11px rgba(0, 0, 0, 0.6); box-shadow: -10px 17px 25px 11px rgba(0, 0, 0, 0.6); transform-origin: center; } .picture2 { } #bigBlock div:nth-child(1) { width: 45%; height: 20%; top: 76%; left: 38%; background-color: #ED5A00; background-position: -165px -295px; z-index: 7; } #bigBlock div:nth-child(2) { width: 55%; height: 25%; top: 50%; left: 5%; background-color: #ED5A00; background-position: 0px -170px; z-index: 6; } #bigBlock div:nth-child(3) { width: 20%; height: 20%; top: 30%; left: 6%; background-color: #ED5A00; background-position: -5px -70px; z-index: 5; } #bigBlock div:nth-child(4) { width: 35%; height: 20%; top: 29%; left: 27%; background-color: #ED5A00; background-position: -110px -70px; z-index: 4; } #bigBlock div:nth-child(5) { width: 15%; height: 20%; top: 27%; left: 63%; background-color: #ED5A00; background-position: -292px -62px; z-index: 3; } #bigBlock div:nth-child(6) { width: 12%; height: 10%; top: 43%; left: 79%; background-color: #ED5A00; background-position: -365px -135px; z-index: 2; } #bigBlock div:nth-child(7) { width: 35%; height: 30%; top: 0%; left: 27%; background-color: #ED5A00; background-position: -110px 70px; z-index: 1; } </style> </head> <body> <div id="field"> <div id="bigBlock"> <div class="block picture2">1</div> <div class="block picture2">2</div> <div class="block picture2">3</div> <div class="block picture2">4</div> <div class="block picture2">5</div> <div class="block picture2">6</div> <div class="block picture2">7</div> </div> </div> </body> </html> window.onload = function () { var $elem = $('#bigBlock div'); $elem.eq(1).changeSizes; function changeSizes() { var oldWidth = $(this).css('width'), oldHeight = $(this).css('height'); if (oldWidth > oldHeight ) { while ($(this).css('width') != oldHeight ) { $(this).css('width')- 1; } while ($(this).css('height') != oldWidth) { $(this).css('height')+ 1; } } else { while ($(this).css('width') != oldHeight ) { $(this).css('width')+ 1; } while ($(this).css('height') != oldWidth) { $(this).css('height')- 1; } } },1000 ); } } Мой код не работает :help: |
changeSizes - Нет такого метода не в JS не jQuery. Создать функцию и объявить у элемента свойство с именем функции недостаточно для того чтоб скрипт понял что вы от него хотите.
jQuery(function ($) { $('#bigBlock div').each(function () { $(this).animate({ width: $(this).height(), height: $(this).width() }, 1000); }); }); |
Спасибо за совет. Вопрос ещё один, как сделать что б они не разом все меняли свои размеры а по очереди. Причём, пока 1 элемент не поменяет ширину на высоту +высоту на ширину, второй не стартует и т.д.
Я пробовал через цикл, но у меня опять же всё присваивается практически одновременно window.onload = function () { var $elem = $('#bigBlock div'); var len = $('#bigBlock div').length; for ( var i=0; i < len; i++ ){ //$elem.eq(i).addClass('animated flip'); changeSizes($elem.eq(i)); function changeSizes(el) { el.animate({ width: el.height(), height: el.width() }, 1000); }; } } |
Цитата:
setTimeout() |
Цитата:
window.onload = function () { var object; var $elem = $('#bigBlock div'); var len = $('#bigBlock div').length; var i = 0; for (i = 0; i < len; i++) { function Change() { $elem.eq(i).addClass('animated flip'); changeSizes($elem.eq(i)); function changeSizes(el) { el.animate({ width: el.height(), height: el.width() }, 1000); }; setTimeout(Change, 1000); } } } |
Black_Star, явный for не нужен. :no:
В самом setTimeout() нужно брать элемент... Что-то с ним делать... Если есть следующий элемент - стартовать следующий setTimeout(). |
Цитата:
С одним элементом у меня через if получилось, window.onload = function () { var $elem = $('#bigBlock div'); var len = $('#bigBlock div').length; var i = 0; if (i <= len) { setTimeout(Change(i), 1000); i = i++; } function Change(i) { $elem.eq(i).addClass('animated flip'); changeSizes($elem.eq(i)); function changeSizes(el) { el.animate({ width: el.height(), height: el.width() }, 1000); } } } |
отложенная анимация css3 js
Black_Star,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #field { position: relative; width: 600px; height: 600px; border: 1px solid black; background-color: red; } #bigBlock { position: relative; width: 500px; height: 500px; border: 1px solid black; margin-top: 5%; margin-left: 5%; /*background: url("snowboarder-400x385.png") 50% 50% no-repeat;*/ } .block { position: absolute; border: 3px solid white; -webkit-box-shadow: -10px 17px 25px 11px rgba(0, 0, 0, 0.6); -moz-box-shadow: -10px 17px 25px 11px rgba(0, 0, 0, 0.6); box-shadow: -10px 17px 25px 11px rgba(0, 0, 0, 0.6); transform-origin: center; transition: all .8s ease-in-out; } .picture2 { } #bigBlock div:nth-child(1) { width: 45%; height: 20%; top: 76%; left: 38%; background-color: #ED5A00; background-position: -165px -295px; z-index: 7; } #bigBlock div:nth-child(2) { width: 55%; height: 25%; top: 50%; left: 5%; background-color: #ED5A00; background-position: 0px -170px; z-index: 6; } #bigBlock div:nth-child(3) { width: 20%; height: 20%; top: 30%; left: 6%; background-color: #ED5A00; background-position: -5px -70px; z-index: 5; } #bigBlock div:nth-child(4) { width: 35%; height: 20%; top: 29%; left: 27%; background-color: #ED5A00; background-position: -110px -70px; z-index: 4; } #bigBlock div:nth-child(5) { width: 15%; height: 20%; top: 27%; left: 63%; background-color: #ED5A00; background-position: -292px -62px; z-index: 3; } #bigBlock div:nth-child(6) { width: 12%; height: 10%; top: 43%; left: 79%; background-color: #ED5A00; background-position: -365px -135px; z-index: 2; } #bigBlock div:nth-child(7) { width: 35%; height: 30%; top: 0%; left: 27%; background-color: #ED5A00; background-position: -110px 70px; z-index: 1; } </style> <script> window.addEventListener('DOMContentLoaded', function() { [].forEach.call( document.querySelectorAll('.block'), function(el,i) { var width = el.scrollWidth, height = el.scrollHeight; el.style.transitionDelay = i + 's'; el.style.width = height+'px'; el.style.height = width+'px'; }); }); </script> </head> <body> <div id="field"> <div id="bigBlock"> <div class="block picture2">1</div> <div class="block picture2">2</div> <div class="block picture2">3</div> <div class="block picture2">4</div> <div class="block picture2">5</div> <div class="block picture2">6</div> <div class="block picture2">7</div> </div> </div> </body> </html> |
Цитата:
|
Black_Star, c таймаутами будет сложнее.
Если сложность - синтаксис, то так должно быть понятнее. var els = document.querySelectorAll('.block'); for (var i = 0; i < els.length; i++) { var el = els[i]; var width = el.scrollWidth, height = el.scrollHeight; el.style.transitionDelay = i + 's'; // 0s, 1s, .... 6s el.style.width = height+'px'; el.style.height = width+'px'; } Если непонятно - что происходит в этом коде, то посмотри на эти элементы в инспекторе. |
Цитата:
|
А если задачу надо усложнить. Как сделать что б через установленный промежуток времени к каждому блоку добавлялся класс с анимацией, причем пока эта анимация не проиграется для этого блока дальше цикл не идет ?
window.onload = function () { var $elem = $('#bigBlock div'); var len = $('#bigBlock div').length; var i = 0; for (i = 0; i < len; i++){ (function(i) { var el = $elem[i]; var width = el.scrollWidth, height = el.scrollHeight; setTimeout(function() { *!* el.addClass('animated flip'); // не работает */!* el.style.width = height+'px'; el.style.height = width+'px'; }, 1000*i); }) (i); } |
Цитата:
выкиньте цикл и запускайте следущую "анимацию" по окончанию предыдущей. гуглить transitionend |
Цитата:
Я наверное как-то криво изъясняюсь. Попробую объяснить все пошагово. 1)Есть большое поле с дивами(у каждого свои размеры и каждый занимает свою позицию в пространстве + каждый див имеет класс picture1); 2)Ждем 2сек (- это время первой задержки, во время нее ничего не происходит) 3) Первому диву данного блока прискаевается классы с анимацией .toggleClass('animated flip') ( время анимации я задаю через CSS свойства, допустим 1,5сек) + класс picture1 заменяется picture2 только у этого дива 4) Первый див меняет свои размеры (высота=ширине, ширина=высоте) 5) Первый (уже измененный) див меняет свое положение в пространстве. #bigBlock .picture2:nth-child(1) { top: 36%; left: 57%; } 6) С первого класса удаляются классы анимации .toggleClass('animated flip') 7) пункты 3-6 проделываются по очереди с каждым дивом до i<$('#bigBlock div').length; 8) Все дивы заняли новые позиции, и у них всех есть класс picture2 . Ждем 2сек. 9)Идет повтор от 3 - 6 для каждого дива . 10) Все дивы заняли новые позиции, и у них всех есть класс picture3 . Ждем 2сек. 11) Цикл продолжается пока не доходит picture N 12) Цикл идет с picture N в picture 1:) |
Black_Star,
пока к пост №13 добавить нечего ... |
Часовой пояс GMT +3, время: 05:00. |