Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Заметки JQuery.docx
Скачиваний:
1
Добавлен:
08.11.2019
Размер:
6.49 Mб
Скачать

Устанавливает таймер задержки выполнения очередных функций-эффектов (следующих пунктов в очереди) для соответствующих элементов набора jQuery.

Passing 1000 to delay will cause it to wait 1 second since its argument is in milliseconds.

// Сначала растворим элемент, id которого имеет значение 'foo',

// а затем через секунду (1000 миллисекунд) проявим его.

$('#foo').fadeOut(300).delay(1000).fadeIn(400);

// Если условие выполняется, дождемся, пока первый элемент

// (с id='test') выкатится, а затем выкатим второй элемент

// (с id='test2'). Если условие false, то второй элемент

// выкатываем сразу без задержек.

if (this.id=='foo')

{

$('#test1').slideDown(500);

$('#test2').delay(500);

}

$('#test2').slideDown(500);

Пошаговое перемещение квадрата:

$(document).ready(function(){

$("#moveMe").click(function(event){

$(this).animate({

left: "100px"

},1500).delay(1000).animate({top: "100px"},1500);

});

});

_____________________________________________________________________________________

fadeIn() fadeOut()

Синий квадрат появляется при клике на секунду и затем исчезает. Код:

$(document).ready(function(){

$('#reveal').click(function(){

$('#block').fadeIn(1000);

$('#block').fadeOut(1000);

});

});

_____________________________________________________________________________________

Show() hide()

Разница между фейнин и шоу в том, что фейд просто делает объект невидимым, но при этом сохраняет размеры.

$(document).ready(function(){

$(".items").mouseover(function() {

$("a", this).show().animate({width: 100});

}).mouseout(function() {

$("a", this).animate({width: 0}, function() {

$(this).hide();

});

});

});

Так же обоим эффектам show() и hide() можно присвоить аргументы slow/ fast. Регулирует скорость исчезновения и появления объекта, к которому применяется данная команда.

_____________________________________________________________________________________

slideUp() and slideDown()

SlideUp() causes an element to have animation where it slides up the screen until it disappears. slideDown() does the opposite. Другими словами объект анимировано скрывается от слайдАп и так же появляется от слайдДавн.

$(document).ready(function(){

$(document).click(function () {

if ($("div:first").is(":hidden")) {

$("div").show("slow");

} else {

$("div").slideUp(); }

});

});

При клике панелька едет вверх и скрывается. При повторном клике по документе – элементы по одному анимировано заполняют все 3 ряды, начиная с левого верхнего угла.

_____________________________________________________________________________________

slideToggle()

Команда принимает аргументы slow/ fast или милисекунды.

$(document).ready(function(){

$(document).keypress(function(event){

//get string of key pressed for easier comparison than keycodes

var keyPressed = String.fromCharCode(event.which);

//attach a handler to the appropriate div.

var $divs = $("div");

switch (keyPressed) {

case "a":

$divs.eq(0).slideToggle("fast");

break;

case "s":

$divs.eq(1).slideToggle(“slow”);

break;

case "d":

$divs.eq(2).slideToggle();

break;

case "f":

$divs.eq(3).slideToggle();

break;

}

});

});

При нажатии клавиш a,s,d,f исчезает и появляется соответсвующий кубик.

_____________________________________________________________________________________

Stop()

A useful function to combine with the things we have learned to this point is the stop function. Stop can be called with 0, 2, or 3 arguments. 0 Will do the simple default action of pausing all animations currently active on the element which it is attached to.

The use of 2 arguments can give the coder control over the entire queue of elements on the element, not just the current item. 3 arguments can be used to specify the queue that you wish to edit, as well as what to do with it.

$(document).ready(function(){

$("#go").click(function(){

$(".block").animate({left: '+=300px'}, 3000);

});

/* Stop animation when button is clicked */

$('#stop').click(function(){

$('.block').stop();

});

/* Start animation in the opposite direction */

$("#back").click(function(){

$(".block").animate({left: '-=300px'}, 3000);

});

});

Управление кубиком с помощью кнопок GO STOP BACK.

_____________________________________________________________________________________

P L U G I N S

Plugins are libraries of code that help automate things we commonly want to do as programmers. Typically a plugin adds even more abilities to an already existing library. In this case we will look at plugins that extend the existing jQuery library.

We've included the jQuery UI library by using <script> tags in the head of the html file. We set the source to be "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js" to include Google's hosting of jQuery UI.

If you are going to use any jQuery functions in your own projects you will have to do this as well.

_____________________________________________________________________________________

.draggable()

$(document).ready(function(){

$("#dragme").draggable();

});

//перестаскивает квадрат зажатым кликом.

_____________________________________________________________________________________

.sortable()

Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable properties.

Другими словами, sortable() позволяет сортировать элементы, перетаскивая их на место после или перед выбранным элементом, при этом не меняя их местами. $(function() {

$('#sortlist').sortable();

});

_____________________________________________________________________________________

.resizable()

Enable any DOM element to be resizable. With the cursor grab the right or bottom border and drag to the desired width or height.

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

$(function () {

$('#resizeMe').resizable();

});

//пример использования. Растягивает куб

_____________________________________________________________________________________

UIs addClass() and removeClass()

Вместо обычного присваивания класса, мы получаем визуальный переход. Чем-то похоже на .animate().

The addClass function in UI can take 3 arguments. $( "#myDiv" ).addClass( "red", 500, callback);

"red" is the class to add to myDiv,

500 is the time for the animation to happen,

callback is the optional function to run at the completion of the animation.

$(function() {

$( "#button" ).click(function() {

$('#writing').addClass("transition",1000,callbackFunction());

});

function callbackFunction() {

setTimeout(function() {

$('#writing').removeClass("transition");},

1500 );}

});

Изменяет свой размер при нажатии кнопки.

_____________________________________________________________________________________

UI’s animate()

Example:

$(this).animate({ backgroundColor: "black" },1000);

Notice how the color black is in quotes like "black". Since you are creating an object, the value needs to be in quotes unless it is a number, otherwise JavaScript will try to interpret it as a part of your program instead of just a value.

$(function () {

$('#button').click( function () {

$('#writing').animate({backgroundColor:'#d4ecf8'},1000);

});

});

Тут и так все понятно хуле.

_____________________________________________________________________________________

Auto-complete widget

The widget suggests answers for the user as they type, if their typing matches one of the known strings we give to the auto-completer.

Тоесть этот виджет пытается угадать строку, которую набирает пользователь и, если такова найдена, оно автоматически дополняет её. Полезная вещь, как не крути.

$(function() {

$('#tags').autocomplete({source : availableTags});

});

Где availableTags – массив.

var availableTags = [

"ActionScript",

"AppleScript",

"Asp",

"BASIC",

"C",

"C++",

"Clojure",

"COBOL",

"ColdFusion",

"Erlang",

"Fortran",

"Groovy",

"Haskell",

"Java",

"JavaScript",

"Lisp",

"Perl",

"PHP",

"Python",

"Ruby",

"Scala",

"Scheme"

];

Неплохо как для парочки строчек кода, ага?:Р

_____________________________________________________________________________________

Datepicker

The datepicker is a common object that can be used to automate the user picking a date. It also takes care of the need for any protections since the user is selecting a date from a list of values that we provide, rather than being able to insert anything they want.

Другими словами, это встроенный объект, представляющий собой календарик.

$(function() {

$('#dateEntry').datepicker();

});

_____________________________________________________________________________________

Slider

Sliders can allow the user to select values without having to enter it themselves, just like a datepicker but it works better for more linear data.

Since it is a jQuery UI component and not a normal HTML input we have to get the value of the slider out by calling slider("value") after selecting the slider with jQuery.

$(function() {

$("#slider").slider({

stop: function ( event, ui ) {

$('#slider').slider("value");

$('#volume').html( $('#slider').slider("value") );

}

});

});

  • To get the value of the slider use $('#slider').slider("value").

  • Then you should put the value in the .html() like this: $('#volume').html( $('#slider').slider("value") )

_____________________________________________________________________________________

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]