Статьи

8 советов и рекомендаций по jQuery

Вот несколько интересных советов и приемов для jQuery. Есть много вещей, которые можно сделать с этой мудрой библиотекой javascript, таких как изменение размера шрифтов, отключение правых кликов и многое другое. Вы также можете сделать пользовательское кодирование JQuery и сделать удивительные сценарии, как этот список, который у меня есть.

1. Изменение размера шрифта

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

КОД:

$(document).ready(function(){ //ID, class and tag element that font size is adjustable in this array //Put in html or body if you want the font of the entire page adjustable var section = new Array('span','.section2'); section = section.join(','); // Reset Font Size var originalFontSize = $(section).css('font-size'); $(".resetFont").click(function(){ $(section).css('font-size', originalFontSize); }); // Increase Font Size $(".increaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*1.2; $(section).css('font-size', newFontSize); return false; }); // Decrease Font Size $(".decreaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*0.8; $(section).css('font-size', newFontSize); return false; }); }); + | - | = Font size can be changed in this section This won't be affected This one is adjustable too! 
$(document).ready(function(){ //ID, class and tag element that font size is adjustable in this array //Put in html or body if you want the font of the entire page adjustable var section = new Array('span','.section2'); section = section.join(','); // Reset Font Size var originalFontSize = $(section).css('font-size'); $(".resetFont").click(function(){ $(section).css('font-size', originalFontSize); }); // Increase Font Size $(".increaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*1.2; $(section).css('font-size', newFontSize); return false; }); // Decrease Font Size $(".decreaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*0.8; $(section).css('font-size', newFontSize); return false; }); }); + | - | = Font size can be changed in this section This won't be affected This one is adjustable too!
$(document).ready(function(){ //ID, class and tag element that font size is adjustable in this array //Put in html or body if you want the font of the entire page adjustable var section = new Array('span','.section2'); section = section.join(','); // Reset Font Size var originalFontSize = $(section).css('font-size'); $(".resetFont").click(function(){ $(section).css('font-size', originalFontSize); }); // Increase Font Size $(".increaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*1.2; $(section).css('font-size', newFontSize); return false; }); // Decrease Font Size $(".decreaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*0.8; $(section).css('font-size', newFontSize); return false; }); }); + | - | = Font size can be changed in this section This won't be affected This one is adjustable too!

2. НАЗАД К верхней кнопке или ссылке

Это очень хороший способ вернуться наверх страницы, используя эффекты прокрутки jQuery для ссылок или кнопок.

КОД:

 $('#top').click(function() { $(document).scrollTo(0,500); } Back to top $('#top').click(function() { $(document).scrollTo(0,500); } Back to top 

3. ОБНАРУЖИТЬ ПРАВЫЙ ЩЕЛК

Важно учитывать правильные клики на веб-сайте. Потому что иногда мы можем захотеть отключить функцию щелчка правой кнопкой мыши на веб-сайте. Итак, вот как мы собираемся определять щелчок правой кнопкой мыши с помощью jQuery.

КОД:

 $(document).bind("contextmenu",function(e){ //you can enter your code here, eg a menu list //cancel the default context menu return false; }); 

4. Открытие в новом окне

Как вы, возможно, знаете, атрибут Target тега «a» в html не проходит проверку W3C, поэтому вы получите здесь несколько ошибок проверки. Этот код jQuery сделает для замены атрибута Target чем-то, что может пройти проверку W3C. Так что здесь идет REL и некоторые коды JQuery.

КОД:

 $('a[rel=external]').attr('target','_blank'); Queness in new window . $('a[rel=external]').attr('target','_blank'); Queness in new window 

5. ПЕРЕКЛЮЧЕНИЕ К РАЗЛИЧНЫМ СТИЛЯМ CSS

Если вы хотите иметь несколько таблиц стилей для своего сайта, эта для вас.

КОД:

 $("a.cssSwitcher").click(function() { //swicth the LINK REL attribute with the value in A REL attribute $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); }); Default Theme Red Theme Blue Theme  $("a.cssSwitcher").click(function() { //swicth the LINK REL attribute with the value in A REL attribute $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); }); Default Theme Red Theme Blue Theme 

6. ПОЛУЧИТЕ X И Y Ось ВАШЕГО МЫШИ

Этот код просто получит координаты указателя мыши.

КОД:

 $().mousemove(function(e){ //display the x and y axis values inside the P element $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); }); 

7. СДЕЛАЙТЕ ЦЕЛЬЮ LI CLICKABLE

Очень полезный прием, когда вы используете список UL для создания навигационного меню. Когда вы нажимаете на область LI (за пределами ссылки), он удивительным образом ищет URL-адрес в теге привязки, а затем выполняет его.

КОД:

 $("ul li").click(function(){ //get the url from href attribute and launch the url window.location=$(this).find("a").attr("href"); return false; }); 

8. КОЛОННЫ РАВНОЙ ВЫСОТЫ

Это очень полезно, особенно если вы хотите, чтобы столбцы имели одинаковую высоту.

КОД:

 $(document).ready(function() { setHeight('.col'); }); //global variable, this will store the highest height value var maxHeight = 0; function setHeight(col) { //Get all the element with class = col col = $(col); //Loop all the col col.each(function() { //Store the highest value if($(this).height() > maxHeight) { maxHeight = $(this).height();; } }); //Set the height col.height(maxHeight); } 
Первый столбец
С двумя линиями
И высота разная

Колонка вторая