Logo
Версия для печати

12 удобных jQuery Snippets для разработчиков №1

  • Автор  SeRbGa

12 удобных jQuery Snippets для разработчиков и дизайнеров. В этом списке предоставлены некоторых полезные JQuery сниппеты, которые довольно часто используются в веб-индустрии и дизайне.

JQuery является кросс-платформенной JavaScript библиотекой, она предназначенна для упрощения клиентских сценариев в HTML. Она была выпущена в январе 2006 года в Нью-Йорке BarCamp NYC by John Resig и находилась под влиянием ранней библиотеки cssQuery Дина Эдвардса. В настоящее время разработан командой разработчиков во главе с Dave Methvin. Используется более чем на 60% из 10 000 самых посещаемых сайтов, JQuery является самой популярной библиотекой JavaScript, используемых сегодня.

Эти удобные jQuery Snippets для разработчиков используются всеми, будь то новичок или профессионал эти фрагменты можно использовать для вашей работы! 

Прикрепить панели навигации наверху при прокрутке вниз

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

<script>
    $(function(){
        var $win = $(window)
        var $nav = $('.mytoolbar');
        var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top;
        var isFixed=0;
 
        processScroll()
        $win.on('scroll', processScroll)
 
        function processScroll() {
            var i, scrollTop = $win.scrollTop()
 
            if (scrollTop >= navTop && !isFixed) {            
                isFixed = 1
                $nav.addClass('subnav-fixed')
            } else if (scrollTop <= navTop && isFixed) {
                isFixed = 0
                $nav.removeClass('subnav-fixed')
            }
        }
 
 
    });
    </script>
<div class="header">
        Header info here. Scroll down to see the effect.
        <div class="mytoolbar">
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </div>
    </div>

 

Простые Вкладки

 

<style>
.tabs > ul li {
	cursor: pointer;
	display: inline-block;
	list-style: none;
	margin: 0;
	text-align: center;
}
.tabs > ul li.active {background: #eee;}
.tabsCont .tab {display: none;}
.tabsCont .tab.active {display: block;}
</style>
<script>
$(document).ready(function() {
    $('.tabs').each(function() {
        var $tabs = $(this),
            $toggles = $tabs.children('ul').find('li'),
            $tab = $tabs.find('.tab');
        $toggles.eq(0).addClass('active');
        $tab.eq(0).addClass('active');
        $toggles.on('click', function() {
            var $this = $(this),
                index = $this.index();
            if(!$this.hasClass('active')) {
                $toggles.removeClass('active');
                $this.addClass('active');
                $tab.hide();
                $tab.eq(index).fadeIn(200);
            }
        });
    });
});
</script>
<div class="tabs">
    <ul>
        <li>Tab 1</li>
        <li>Tab 2</li>
    </ul>
    <div class="tabsCont">
        <div class="tab">first</div>
        <div class="tab">Second</div>
    </div>
</div>

 

Проверка Dropdown

Заставить пользователя сделать выбор из выпадающего меню. Кнопка Отправить будет отключена, пока пользователь не сделает выбор.

 

$(document).ready(function() {
	formButton = $('div.service-form form button');
	$(formButton).attr('disabled','');
	
	$('#swcwidget_53_6').on('change', function(){
	var currentText = $('#swcwidget_53_6 option:selected').text();
	console.log('change!');
		if(currentText == 'Please Select') {
			$(formButton).attr('disabled','');
		} else {
			$(formButton).removeAttr('disabled');
		}
	});
});

 

Открывание всех внешние ссылки в новом окне

 

$('a').each(function() {
	// The link's href
	var theHref = $(this).attr('href').toLowerCase();
	// The current domain
	var currentDomain = window.location.host;
    // Kill any subdomains
    var noSubDomain = currentDomain.match(/[^\.]*\.[^.]*$/)[0];
    // Create a new (case insensitive) regex from the clean domain
	var theDomain = new RegExp(noSubDomain, 'gi');
	if(/^https?/gi.test(theHref)) {
		// This link is using HTTP/HTTPs and is probably external
		if(theDomain.test(theHref)) {
			// Do nothing. For some reason, this site is using absolute internal links         
        } else {
			$(this).attr('target', '_blank');
		}
	}
});

 

Jquery Выпадающая Навигация при наведении курсора

jQuery URL Parameters

 

//Function
(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);
//USAGE
$.QueryString["MyParam"]

 

Простая подсказка на JQuery

 

<script>
$.fn.tooltip = function(showTime, hideTime) {
	if(typeof showTime === "undefined") showTime = 200;
	if(typeof hideTime === "undefined") hideTime = 200;
	var $this = $(this);
	$this.hover(function() {
		var offsetLeft = parseInt($this.offset().left);
			offsetTop = parseInt($this.offset().top),
			text = $this.attr('title');
		$this.removeAttr('title');
		$('body').append('<div class="tooltip">'+text+'</div>');
		$('.tooltip').css({
			left: offsetLeft-$('.tooltip').width()/2,
			top: offsetTop-$('.tooltip').outerHeight()-15
		}).animate({
			opacity: 1,
			top: offsetTop-$('.tooltip').outerHeight()-10
		}, showTime);
	}, function() {
		$(this).attr('title', text);
		$('.tooltip').animate({
			opacity: 0,
			top: offsetTop-$('.tooltip').outerHeight()-15
		}, hideTime, function() {
			$(this).remove();
		});
	});
};
// Example:
// $('.tt[title]').tooltip(200,200); 
</script>
<style>
/* LESS */
.tooltip {
	background: #434a54;
	color: #fff;
	display: inline-block;
	font-size: 14px;
	line-height: 16px;
	max-width: 200px;
	min-width: 80px;
	opacity: 0;
	padding: 5px 10px;
	position: absolute;
	z-index: 999;
	.border-radius(2px);
	.box-shadow(0 0 10px #fff);
	.tac;
	&:after {
		border-top: 6px solid #434a54;
		border-left: 6px solid transparent;
		border-right: 6px solid transparent;
		content: '';
		display: block;
		margin: 0 0 0 -6px;
		position: absolute;
		left: 50%;
		bottom: -6px;
	}
}
</style>

 

JQuery Rotator изображений с ссылками

Автоматическое добавление Class Lightbox

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

 

$('div.entry-content a img').each(function() {
	// The href of the link	
	var theImageLink = $(this).parent("a").attr("href");
	// The link itself
	var theParent = $(this).parent("a");
	// Test the link to see if it's actually an image
	if ( !/\.(jpg|jpeg|gif|png)$/i.test(theImageLink) ) {
			// This isn't an image link, follow the href 
		} else {
			$(theParent).addClass('lbimage');
	}
});

 

JQuery Color Changer быстрого функционирования

 

function elementColorChange (element, newColor, originalColor, newFontColor, originalFontColor) {
$(element).hover(function() {
	$(this).stop(true, true).animate ({
 		backgroundColor: newColor,
		color: newFontColor
	}, 200)
 }, function (){
	$(this).stop(true, true).animate ({
		backgroundColor: originalColor,
		color: originalFontColor
	}, 200)
 });
 }

 

Jquery бесконечная прокрутка с помощью AJAX

 

function elementColorChange (element, newColor, originalColor, newFontColor, originalFontColor) {
 $(element).hover(function() {
	$(this).stop(true, true).animate ({
		backgroundColor: newColor,
		color: newFontColor
 
 	}, 200)
 }, function (){
 	$(this).stop(true, true).animate ({
 		backgroundColor: originalColor,
 		color: originalFontColor
 	}, 200)
 });
 }
Последнее изменениеВторник, 02 Сентябрь 2014 12:51
  • Оцените материал
    (1 Голосовать)
  • Опубликовано в Web coding
  • Прочитано 2471 раз
SeRbGa

SeRbGa

мечтатель

Сайт: www.serbga.ru

Оставить комментарий

SeRbGa