- PVSM.RU - https://www.pvsm.ru -
JavaScript-библиотека jQuery становится все популярнее, и в этой заметке я собрал простые jquery-сниппеты, с помощью которых можно значительно улучшить удобство работы с сайтом.
Помогает загружать необходимые изображения на странице заранее. [Источник [1]]
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
Этот сниппет открывает в новом окне все ссылки с параметром rel=«external». [Источник [2]]
$('a[@rel$='external']').click(function(){
this.target = "_blank";
});
/*
Usage:
<a href="http://www.catswhocode.com" rel="external">catswhocode.com</a>
*/
Очень простой код, всего в одну строку, который определяет, работает ли JavaScript у пользователя, и назначает определенный класс hasJS тегу body. [Источник [3]]
$('body').addClass('hasJS');
Позволяет выравнивать высоту колонок на странице. [Источник [4]]
var max_height = 0;
$("div.col").each(function(){
if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);
Помогает устаревшим браузерам понимать разметку HTML. [Источник [5]]
(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}})()
Лучше использовать так:
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
С помощью этого кода, можно проверить поддержку определенного CSS3-свойства в браузере. В примере проверяется border-radius. [Источник [6]]
var supports = (function() {
var div = document.createElement('div'),
vendors = 'Khtml Ms O Moz Webkit'.split(' '),
len = vendors.length;
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
// browser supports box-shadow. Do what you need.
// Or use a bang (!) to test if the browser doesn't.
return true;
}
}
return false;
};
})();
if ( supports('textShadow') ) {
document.documentElement.className += ' textShadow';
Назначение событий определенным клавишам. [Источник [7]]
$('input').keydown(function(e) {
// variable e contains keystroke data
// only accessible with .keydown()
if(e.which == 11) {
e.preventDefault();
}
});
$('input').keyup(function(event) {
// run other event codes here
});
Позволяет управлять поведением элемента при наведении курсора мыши. [Источник [8]]
$("a").hover(
function () {
// code on hover over
},
function () {
// code on away from hover
}
);
Картинка тускнеет при наведении курсора мыши. [Источник [9]]
$(document).ready(function(){
$(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads
$(".thumbs img").hover(function(){
$(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
},function(){
$(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout
});
});
Простое получение параметров URL страницы. [Источник [10]]
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;
}
Простой, но мощный способ реализовать скролл к началу документа. [Источник [11]]
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
Позволяет плавно переключаться к нужной части документа. [Источник [12]]
$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});
Позволяет изменить CSS-класс нужного элемента, бывает полезно например для пунктов меню. [Источник [13]]
$('nav a').toggleClass('selected');
Отключает клавишу Enter в форме. [Источник [14]]
$("#form").keypress(function(e) {
if (e.which == 13) {
return false;
}
});
Использованные материалы:
Автор:
Источник [18]
Сайт-источник PVSM.RU: https://www.pvsm.ru
Путь до страницы источника: https://www.pvsm.ru/jquery/20724
Ссылки в тексте:
[1] Источник: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
[2] Источник: http://snipplr.com/view/315/-jquery--target-blank-links/
[3] Источник: http://eisabainyo.net/weblog/2010/09/01/10-useful-jquery-snippets/
[4] Источник: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/
[5] Источник: http://remysharp.com/2009/01/07/html5-enabling-script/
[6] Источник: http://snipplr.com/view/44079
[7] Источник: http://api.jquery.com/keydown/
[8] Источник: http://api.jquery.com/hover/
[9] Источник: http://snipplr.com/view/18606/
[10] Источник: http://snipplr.com/view/26662
[11] Источник: http://stackoverflow.com/questions/1144805/how-do-i-scroll-to-the-top-of-the-page-with-jquery/1145297#1145297
[12] Источник: http://snipplr.com/view.php?codeview&id=26739
[13] Источник: http://api.jquery.com/toggleClass/
[14] Источник: http://snipplr.com/view/10943/disable-enter-via-jquery/
[15] 10 awesome jQuery snippets: http://www.catswhocode.com/blog/10-awesome-jquery-snippets
[16] 14 Handy jQuery Code Snippets for Developers: http://blog.teamtreehouse.com/14-handy-jquery-code-snippets-for-developers
[17] Snipplr.com: http://snipplr.com
[18] Источник: http://habrahabr.ru/post/159703/
Нажмите здесь для печати.