Архив

Публикации с меткой ‘javascript’
function number_format(number,decimals,dec_point,thousands_sep){
	number=(number+'').replace(/[^0-9+\-Ee.]/g,'');
	var n=!isFinite(+number)?0:+number,
	prec=!isFinite(+decimals)?0:Math.abs(decimals),
	sep=(typeof thousands_sep==='undefined')?',':thousands_sep,
	dec=(typeof dec_point==='undefined')?'.':dec_point,
	s='',
	toFixedFix=function(n,prec){
		var k=Math.pow(10,prec);
		return ''+Math.round(n*k)/k;
	};
	s=(prec?toFixedFix(n,prec):''+Math.round(n)).split('.');
	if(s[0].length>3){
		s[0]=s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,sep);
	}
	if((s[1]||'').length<prec){
		s[1]=s[1]||'';
		s[1]+=new Array(prec-s[1].length+1).join('0');
	}
	return s.join(dec);
}

Добавлено:
Еще варианты:

function number_format(str){
	return str.replace(/(\s)+/g,'').replace(/(\d{1,3})(?=(?:\d{3})+$)/g,'$1 ');
}
function number_format(number,decimals,dec_point,thousands_sep){
	var i,j,kw,kd,km;
	if(isNaN(decimals=Math.abs(decimals))){
		decimals=2;
	}
	if(dec_point==undefined){
		dec_point=",";
	}
	if(thousands_sep==undefined){
		thousands_sep=".";
	}
	i=parseInt(number=(+number||0).toFixed(decimals))+"";
	if((j=i.length)>3){
		j=j%3;
	}else{
		j=0;
	}
	km=(j?i.substr(0,j)+thousands_sep:"");
	kw=i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+thousands_sep);
	kd=(decimals?dec_point+Math.abs(number-i).toFixed(decimals).replace(/-/,0).slice(2):"");
	return km+kw+kd;
}

Почти как первый (не проверен):

function number_format(number,decimals,dec_point,thousands_sep){
	number=(number+'').replace(/[^0-9+\-Ee.]/g,'');
	var n=!isFinite(+number)?0:+number,
	prec=!isFinite(+decimals)?0:Math.abs(decimals),
	sep=(typeof thousands_sep==='undefined')?',':thousands_sep,
	dec=(typeof dec_point==='undefined')?'.':dec_point,
	s='',
	toFixedFix=function(n,prec){
		var k=Math.pow(10,prec);
		return ''+(Math.round(n*k)/k).toFixed(prec);
	};
	s=(prec?toFixedFix(n,prec):''+Math.round(n)).split('.');
	if(s[0].length>3){
		s[0]=s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,sep);
	}
	if((s[1]||'').length<prec){
		s[1]=s[1]||'';
		s[1]+=new Array(prec-s[1].length+1).join('0');
	}
	return s.join(dec);
}
Categories: Javascript Tags:

Действия при сворачивании и разворачивании блока..

function ToggleHSL() {
	$('#hsl').slideToggle('normal',function(){
		if ($(this).is(':hidden')) {
			$('#top').css('margin-top','0px');
		} else {
			$('#top').css('margin-top','-216px');
		}
		return false;
	});
}

http://www.sitepoint.com/forums/showthread.php?572201-jquery-finding-the-state-of-slideToggle

Categories: Javascript Tags: ,
28 марта 2013 Нет комментариев

В примере плавное изменение прозрачности блока при наведении мышки, от 0.5 до 1. 250 — это скорость изменения.

$(document).ready(function() {
	var opacity=0.5,toOpacity=1,duration=250;
	$('.inf').css('opacity',opacity).hover(function() {
		$(this).fadeTo(duration,toOpacity);
		}, function() {
			$(this).fadeTo(duration,opacity);
		}
	);
});
Categories: Javascript Tags:
28 марта 2013 Нет комментариев

Аналог для firefox innerTexttextContent. Использование:

var cnt=document.getElementById('containterid');
if (typeof(cnt.innerText)!='undefined') {
	cnt.innerText='newtext';
}
else {
	cnt.textContent='newtext';
}
Categories: Javascript Tags:
28 марта 2013 Нет комментариев

Задача присвоить нужному option атрибут selected.

var sel=document.getElementById('selectid');
sel.options[10].setAttribute("selected","selected");

Специально для firefox добавляем строчку:

sel.options[10].selected=true;
Categories: Javascript Tags:
27 марта 2013 1 комментарий

Функция возвращает размеры рабочей области окна и размеры загруженной страницы сайта:

function  getPageSize(){
	var xScroll, yScroll, pageWidth, pageHeight, windowWidth, windowHeight;
 
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
		xScroll = document.documentElement.scrollWidth;
		yScroll = document.documentElement.scrollHeight;
	} else { // Explorer Mac...would also work in Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
 
	if (self.innerHeight) { // all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
 
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}
 
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
 
	return [pageWidth,pageHeight,windowWidth,windowHeight];
}

Источник: http://www.jstoolbox.com/skripty/raznoe/poluchenie-razmera-stranicy/
Использование — в примере alert, когда высота страницы больше высоты рабочей области окна, т.е. есть вертикальная полоса прокрутки:
перед закрытием body

<script type="text/javascript">
	var ps=getPageSize();
	if (ps[1]>ps[3]) {
		alert(">");
	}
</script>
Categories: Javascript Tags:
21 марта 2013 1 комментарий

order_from и order_to — массивы, содержащие значения дней, месяцов и лет периодов.

На выходе:

  • order_days — интервал в днях;
  • budn — количество будней;
  • vyh — количество выходных.
var time_from=new Date(order_from['y'],order_from['m']-1,order_from['d']);
var time_to=new Date(order_to['y'],order_to['m']-1,order_to['d']);
var order_days=Math.floor((time_to.getTime()-time_from.getTime())/(1000*60*60*24));
var getday=new Date();
var vyh=0;
var curday;
for (i=0;i<=order_days;i++) {
	//getday.setDate(time_from.getDate()+i);
	getday.setTime(time_from.getTime()+((1000*3600*24)*i));
	curday=getday.getDay();
	if ((curday==0)||(curday==6)) {
		vyh++;
	}
}
var budn=order_days;
budn=budn-vyh;
Categories: Javascript Tags: