Jquery css height animated

Выполнение пользовательской анимации

Выполняет заданную пользователем анимацию, с выбранными элементами. Анимация происходит за счет плавного изменения CSS-свойств у элементов. Функция имеет два варианта использования:

properties — список CSS-свойств, участвующих в анимации и их конечных значений. (см. описание ниже)
duration — продолжительность выполнения анимации. Может быть задана в миллисекундах или строковым значением ‘fast’ или ‘slow’ (200 и 600 миллисекунд).
easing — изменение скорости анимации (будет ли она замедляется к концу выполнения или наоборот ускорится). (см. описание ниже)
callback — функция, которая будет вызвана после завершения анимации.

properties — список CSS-свойств, участвующих в анимации и их конечных значений. (см. описание ниже)
options — дополнительные опции. Должны быть представлены объектом, в формате опция:значение. Варианты опций:

duration — продолжительность выполнения анимации (см. выше). easing — изменение скорости анимации (будет ли она замедляется к концу выполнения или наоборот ускориться). (см. описание ниже) complete — функция, которая будет вызвана после завершения анимации. step — функция, которая будет вызвана после каждого шага анимации. queue — булево значение, указывающее, следует ли помещать текущую анимацию в очередь функций. В случае false, анимация будет запущена сразу же, не вставая в очередь. specialEasing — позволяет установить разные значения easing, для разных CSS-параметров. Задается объектом, в формате параметр:значение. Опция была добавлена в jQuery 1.4.

Выполнение нескольких анимаций

При одновременном вызове нескольких эффектов, применительно к одному элементу, их выполнение будет происходить не одновременно, а поочередно. Например при выполнении следующих команд:

$("#my-div").animate({height: "hide"}, 1000); $("#my-div").animate({height: "show"}, 1000);

элемент с идентификатором my-div, в начале будет плавно исчезать с экрана, а затем начнет плавно появляться вновь. Однако, анимации, заданные на разных элементах, будут выполняться одновременно:

$("#my-div-1").animate({height: "hide"}, 1000); $("#my-div-2").animate({height: "show"}, 1000);

Параметр properties

Задается объектом, в формате css-свойство:значение. Это очень похоже на задание группы параметров в методе .css(), однако, properties имеет более широкий диапазон типов значений. Они могут быть заданы не только в виде привычных единиц: чисел, пикселей, процентов и др., но еще и относительно: (увеличит высоту на 30 пикселей и сместит вправо на 40). Кроме того, можно задавать значения "hide", "show", "toggle", которые скроют, покажут или изменят видимость элемента на противоположную, за счет параметра, к которому они применены. Например

$('div').animate( { opacity: "hide", height: "hide" }, 5000);

Скроет div-элементы, за счет уменьшения прозрачности и уменьшения высоты (сворачиванием) элемента.

Замечание 1: Отметим, что в параметре properties можно указывать только те css-свойства, которые задаются с помощью числовых значений. Например, свойство background-color использовать не следует.

Замечание 2: Величины, которые в css пишутся с использованием дефиса, должны быть указаны без него (не margin-left, а marginLeft).

Читайте также:  Java collection framework tutorial

Обработчик завершения анимации

Функция, заданная в качестве обработчика завершения анимации не получает параметров, однако, внутри функции, переменная this будет содержать DOM-объект анимируемого элемента. Если таких элементов несколько, то обработчик будет вызван отдельно, для каждого элемента.

Параметр easing

Этот параметр определяет динамику выполнения анимации — будет ли она проходить с замедлением, ускорением, равномерно или как то еще. Параметр easing задают с помощью функции. В стандартном jQuery доступны лишь две такие функции: 'linear' и 'swing' (для равномерной анимации и анимации с ускорением). По умолчанию, easing равняется 'swing'. Другие варианты можно найти в плагинах, например, jQuery UI предоставляет более 30 новых динамик.

Существует возможность задавать разные значения easing для разных css-свойств, при выполнении одной анимации. Для этого нужно воспользоваться вторым вариантом функции animate() и задать опцию specialEasing. Например:

$('#clickme').click(function() { $('#book').animate({ opacity: 'toggle', height: 'toggle' }, { duration: 5000, specialEasing: { opacity: 'linear', height: 'swing' } }); });

в этом случае изменение прозрачности будет происходить равномерно (linear), а высота будет изменяться с разгоном в начале и небольшим торможением в конце (swing).

В действии

При нажатии на кнопку, произведем некоторые манипуляции с элементом, используя метод animate:

~lt~!DOCTYPE html~gt~ ~lt~html~gt~ ~lt~head~gt~ ~lt~style~gt~ div < background-color:#bca; width:100px; border:1px solid green; >~lt~/style~gt~ ~lt~script src="https://code.jquery.com/jquery-latest.min.js"~gt~~lt~/script~gt~ ~lt~/head~gt~ ~lt~body~gt~ ~lt~button ~gt~» Съешь пирожок~lt~/button~gt~ ~lt~div ~gt~Алиса~lt~/div~gt~ ~lt~script~gt~ // Произведем изменение нескольких css-величин в ходе одной анимации. $("#go").click(function()< $("#block").animate(< width: "70%", // ширина станет 70% opacity: 0.4, // прозрачность будет 40% marginLeft: "0.6in", // отступ от левого края элемента станет равным 6 дюймам fontSize: "3em", // размер шрифта увеличится в 3 раза borderWidth: "10px" // толщина рамки станет 10 пикселей >, 1500); // анимация будет происходить 1,5 секунды >); ~lt~/script~gt~ ~lt~/body~gt~ ~lt~/html~gt~

Ссылки

  • пользовательская анимация
  • выполнение анимации
  • анимация заданная пользователем
  • эффекты заданные пользователем
  • .animate()
  • animate()

Источник

jQuery Effects - Animation

The jQuery animate() method is used to create custom animations.

The required params parameter defines the CSS properties to be animated.

The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the animation completes.

The following example demonstrates a simple use of the animate() method; it moves a element to the right, until it has reached a left property of 250px:

Example

By default, all HTML elements have a static position, and cannot be moved.
To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!

jQuery animate() - Manipulate Multiple Properties

Notice that multiple properties can be animated at the same time:

Example

Is it possible to manipulate ALL CSS properties with the animate() method?

Yes, almost! However, there is one important thing to remember: all property names must be camel-cased when used with the animate() method: You will need to write paddingLeft instead of padding-left, marginRight instead of margin-right, and so on.

Читайте также:  Java password hashing function

Also, color animation is not included in the core jQuery library.
If you want to animate color, you need to download the Color Animations plugin from jQuery.com.

jQuery animate() - Using Relative Values

It is also possible to define relative values (the value is then relative to the element's current value). This is done by putting += or -= in front of the value:

Example

jQuery animate() - Using Pre-defined Values

You can even specify a property's animation value as " show ", " hide ", or " toggle ":

Example

jQuery animate() - Uses Queue Functionality

By default, jQuery comes with queue functionality for animations.

This means that if you write multiple animate() calls after each other, jQuery creates an "internal" queue with these method calls. Then it runs the animate calls ONE by ONE.

So, if you want to perform different animations after each other, we take advantage of the queue functionality:

Example 1

The example below first moves the element to the right, and then increases the font size of the text:

Example 2

jQuery Exercises

jQuery Effects Reference

For a complete overview of all jQuery effects, please go to our jQuery Effect Reference.

Источник

Understanding jQuery animate() function

jQuery animate() function is very powerful API to manipulate html elements and add animation functionality. The use of animate function is very simple. First lets check the syntax of this function. .animate( properties, [ duration ], [ easing ], [ callback ] )

  • properties: A map of CSS properties that the animation will move toward.
  • duration: A string or number determining how long the animation will run.
  • easing: A string indicating which easing function to use for the transition.
  • callback: A function to call once the animation is complete.

.animate( properties, options )

  • properties: A map of CSS properties that the animation will move toward.
  • options: A map of additional options to pass to the method. Supported keys:
    • duration: A string or number determining how long the animation will run.
    • easing: A string indicating which easing function to use for the transition.
    • complete: A function to call once the animation is complete.
    • step: A function to be called after each step of the animation.
    • queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately.
    • specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions (added 1.4).

Lets learn the animate() function with set of examples. First include the jQuery javascript library in your html file. Add following in your html tag:

SCRIPT type="text/javascript" src="http://code.jquery.com/jquery-latest.js"> SCRIPT>
Code language: HTML, XML (xml)

For all the demos, we will use a sample DIV tag for animating. Following is the div code and its stylesheet.

style type="text/css"> #content < background-color:#ffaa00; width:300px; height:30px; padding:3px; > style> input type="button" id="animate" value="Animate"/> div id="content">Animate Height div>
Code language: HTML, XML (xml)

Animate height/width

Animating height and width in jQuery is very easy. Lets assume you have a DIV that you want to animate i.e. increase the height.

$("#animate").click(function( ) < $("#content").animate( "height": "80px">, "fast"); >);
Code language: JavaScript (javascript)
$("#animate").click(function( ) < $("#content").animate( "width": "350px">, "fast"); >);
Code language: JavaScript (javascript)

Animate opacity

$("#animate").click(function( ) < $("#content").animate( "opacity": "0.15">, "slow"); >);
Code language: JavaScript (javascript)

Moving elements using animate()

STYLE> #content < background-color:#6688ff; position:absolute; width:100px; height:100px; padding:3px; margin-top:5px; left: 100px; > STYLE> input type="button" id="left" value="Left"/> input type="button" id="right" value="Right"/> div id="content">Move div>
Code language: HTML, XML (xml)
$("#right").click(function( ) < $("#content").animate( "left": "+=50px">, "slow"); >); $("#left").click(function( ) < $("#content").animate( "left": "-=50px">, "slow"); >);
Code language: JavaScript (javascript)

Callback Function

Callback functions are very useful to perform certain activity when the animation is completed. Also note here when multiple elements are mapped with the animation and we have specified a callback function. Then the callback will get called for each of the element. Let us see an example where we use callback function to display a message when animation is completed.

$("#animate").click(function( ) < $("#content").animate( "height": "100px", "width": "250px">, "slow", function( )< $(this).html("Animation Completed"); >); >);
Code language: JavaScript (javascript)

Combine multiple animations

You may want to combine multiple animations. Following are few demos will help you understanding this. Example 1: Animate both height and width at same time. This example is pretty straight forward. You can animate both height and width at same time by specifying it in animate function. For example: In below code we specified height and width value in animate function.

$("#animate").click(function( ) < $("#content").animate( "height": "100px", "width": "250px">, "slow", ); >);
Code language: JavaScript (javascript)
$("#animate").click(function( ) < $("#content") .animate("height": "100px">, 500) .animate("width": "250px">, 500); >);
Code language: JavaScript (javascript)

Queuing of Events

In above demo (Demo 6) we saw that when we queued up the events with multiple .animate() method call, the animation is actually queued up. i.e. it completes the first animation and then proceed with next. Let see an example were we use queue parameter to disable queuing. In following example we have set parameter queue to false . The code is exactly same as demo 6, only change we added is queue = false. Also note that queue parameter is added with second argument.

$("#animate").click(function( ) < $("#content") .animate("height": "100px">, "queue": false, "duration": 500>) .animate("width": "250px">, 500); >);
Code language: JavaScript (javascript)

Источник

Оцените статью