My:JS — различия между версиями

Материал из synset
Перейти к: навигация, поиск
(→‎Массивы)
Строка 152: Строка 152:
  
 
== Примеры ==
 
== Примеры ==
 +
<pre class="brush:js; gutter: false;">
 +
/*
 +
<body onload="slider('slider',1)">
 +
 +
<div id="slider">
 +
 +
  <div class="header"  id="one-header"> Заголовок </div>
 +
  <div class="content" id="one-content">
 +
      <div class="text"> текст    </div>
 +
  </div>
 +
 +
</div>
 +
*/
 +
 +
var array = new Array();
 +
var speed = 5;
 +
var timer = 10;
 +
 +
//-------------------------------------------------------------------------
 +
// Loop through all the divs in the slider parent div
 +
// Calculate seach content divs height and set it to a variable
 +
function slider(target, showfirst)
 +
{
 +
  var slider = document.getElementById(target);   
 +
  var divs = slider.getElementsByTagName('div');
 +
  var divslength = divs.length;
 +
  for(i = 0; i < divslength; i++) {              // бежим по массиву блокв
 +
      var div = divs[i];
 +
      var divid = div.id;
 +
      if(divid.indexOf("header") != -1)
 +
        div.onclick = new Function("processClick(this)");
 +
      else if(divid.indexOf("content") != -1) {
 +
        var section = divid.replace('-content','');
 +
        array.push(section);
 +
        div.maxh = div.offsetHeight;
 +
        if(showfirst == 1 && i == 1)
 +
            div.style.display = 'block';
 +
          else
 +
            div.style.display = 'none';
 +
      }
 +
  }
 +
}
 +
//---------------------------------------------------------------------------
 +
// Process the click - expand the selected content and collapse the others
 +
function processClick(div)
 +
{
 +
  var catlength = array.length;
 +
  for(i = 0; i < catlength; i++) {
 +
      var section = array[i];
 +
      var head = document.getElementById(section + '-header');
 +
      var cont = section + '-content';
 +
      var contdiv = document.getElementById(cont);
 +
      clearInterval(contdiv.timer);
 +
      if(head == div && contdiv.style.display == 'none') {
 +
        contdiv.style.height = '0px';
 +
        contdiv.style.display = 'block';
 +
        initSlide(cont,1);
 +
      }
 +
      else if(contdiv.style.display == 'block')
 +
        initSlide(cont,-1);
 +
  }
 +
}
 +
//---------------------------------------------------------------------------
 +
// Setup the variables and call the slide function
 +
function initSlide(id,dir)
 +
{
 +
  var cont = document.getElementById(id);
 +
  var maxh = cont.maxh;
 +
  cont.direction = dir;
 +
  cont.timer = setInterval("slide('" + id + "')", timer);
 +
}
 +
//---------------------------------------------------------------------------
 +
// Collapse or expand the div by incrementally changing the divs height and opacity
 +
function slide(id)
 +
{
 +
  var cont = document.getElementById(id);
 +
  var maxh = cont.maxh;
 +
  var currheight = cont.offsetHeight;
 +
  var dist;
 +
  if(cont.direction == 1)
 +
      dist = (Math.round((maxh - currheight) / speed));
 +
  else
 +
      dist = (Math.round(currheight / speed));
 +
  if(dist <= 1)
 +
    dist = 1;
 +
 +
  cont.style.height = currheight + (dist * cont.direction) + 'px';
 +
  cont.style.opacity = currheight / cont.maxh;
 +
  cont.style.filter = 'alpha(opacity=' + (currheight * 100 / cont.maxh) + ')';
 +
  if(currheight < 2 && cont.direction != 1) {
 +
      cont.style.display = 'none';
 +
      clearInterval(cont.timer);
 +
  }
 +
  else if(currheight > (maxh - 2) && cont.direction == 1)
 +
      clearInterval(cont.timer);
 +
}
 +
//---------------------------------------------------------------------------
 +
</div>
  
 
== Ссылки ==
 
== Ссылки ==

Версия 09:04, 15 июля 2011

Введение

Подключение к html-файлу файла со скриптом происходит в разделе заголовка:

 
<head>
    <script type="text/javascript" src="script.js"></script>
</head>

Там же можно размещать непосредственно скрипт:

 
<head>
   <script language="javascript">
      document.write("Моя первая страница.");
    </script>
</head>

Эта программа, используя объект document (текущий в браузере) и его метод write пишет на экране текст. Данный сценарий выполняется сразу при открытии документа. В этом же скрипте могут находится функции, которые вызываются при возникновении тех или иных событий, например, при клике на некоторой группе:

 
<div onClick="showMessage();">Текст</div>

Если в head (или подключаемом файле) описана функция:

 
function showMessage()
{
  alert ("Вы щелкнули по div-у");
}

при клике на тексте выскочит окошко.

Работа с формами

Форма перемножающая два числа

 
<form name="form_add">
    <input type="text" name="t1" size="10"> * <input type="text" name="t2" size="10"> 
    <input type="button" name="button" value="=" onClick="Mult();">
    <input type="text" name="res" size="10">
</form>

Скрипт:

 
function Mult()
{
   var a= document.form_add.t1.value;
   var b= document.form_add.t2.value;
   document.form_add.res.value=a*b;
}

Передача имени формы

 
<input type="button" name="button" value="=" onClick="Mult(form_add);">

и функцию написать так:

 
function Mult(obj)
{
   obj.res.value=obj.t1.value * obj.t2.value;
}

Использование getElementById

 
<script type="text/javascript">
function notEmpty(){
	var myTextField = document.getElementById('myText');
	if(myTextField.value != "")
		alert("You entered: " + myTextField.value)
	else
		alert("Would you please enter some text?")		
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Form Checker' />

События

  • onClick
  • onMouseUp
  • onMouseOver
  • onMouseOut

Математика

 
   var s=Math.sqrt(2);  // корень квадратный
   s=s.toFixed(2);      // округление до 2-х цифр после точки

Массивы

 
   var users = new Array("Artem", "Irina", "Sergey", "Boris"); // задание элементов
   var users = new Array(4);                                   // массив из 4-х элементов
   var users = new Array();                                    // просто массив
   users[users.length-1] = "Masha";                            // доступ к последнему элементу

   var a=new Array(1, 2, 3);
   var b=new Array(4, 5, 6);
   var c=a.concat(b);                                           // объединение 2-х массивов
   var c=с.sort();                                              // сортировка

Строки

 
   var s = newString("Итого:");

Методы объекта строка:

  • charAt(n) - возвращает символ, позицию которого определяет параметр n.
  • substr(n1,n2) - возвращает подстроку из строки, где n1 - позиция первого символа подстроки, а n2 - количество символов в строке.

Функции:

  • Number(s) - преобразует строковый параметр s в число.
  • String(n) - преобразует число n в строку.
  • isNaN(s) - проверяет является ли параметр s числом. Если параметр s не является числом, то возвращает значение true (истина), в противном случае - false (ложь).

Дата - время

Методы объекта Date

  • getDate - возвращает число в диапазоне от 1 до 31, представляющее число месяца.
  • getHours - возвращает час суток в диапазоне от 0 (полночь) до 23.
  • getMinutes - возвращает минуты в диапазоне от 0 до 59.
  • getSeconds - возвращает секунды в диапазоне от 0 до 59.
  • getDay - возвращает день недели, как целое число от 0 (воскресенье) до 6 (суббота).
  • getMonth - возвращает номер месяца в году, как целое число от 0 (январь) до 11 (декабрь).
  • getYear - возвращает год в виде двух последних цифр (getFullYear - возвращает год в виде четырех цифр).
 
   var t=new Date();
   var result=t.getHours()+":"+t.getMinutes()+":"+t.getSeconds();

Задание даты:

 
   var t=new Date("Feb,10,1975 17:45:10");

или функциями:

  • setDate - устанавливает число месяца в диапазоне от 1 до 31.
  • setHours - устанавливает час для текущего времени в диапазоне от 0 (полночь) до 23.
  • setMinutes - устанавливает минуты в диапазоне от 0 до 59.
  • setSeconds - устанавливает секунды в диапазоне от 0 до 59.
  • setYear - устанавливает значение года.
  • setMonth - устанавливает значение месяца в диапазоне от 0 (январь) до 11 (декабрь).
  • setTime - устанавливает значение объекта Date и возвращает количество миллисекунд, прошедших с 1 января 1970 года.


Примеры

 
/*
<body onload="slider('slider',1)">

Заголовок
текст
*/ var array = new Array(); var speed = 5; var timer = 10; //------------------------------------------------------------------------- // Loop through all the divs in the slider parent div // Calculate seach content divs height and set it to a variable function slider(target, showfirst) { var slider = document.getElementById(target); var divs = slider.getElementsByTagName('div'); var divslength = divs.length; for(i = 0; i < divslength; i++) { // бежим по массиву блокв var div = divs[i]; var divid = div.id; if(divid.indexOf("header") != -1) div.onclick = new Function("processClick(this)"); else if(divid.indexOf("content") != -1) { var section = divid.replace('-content',); array.push(section); div.maxh = div.offsetHeight; if(showfirst == 1 && i == 1) div.style.display = 'block'; else div.style.display = 'none'; } } } //--------------------------------------------------------------------------- // Process the click - expand the selected content and collapse the others function processClick(div) { var catlength = array.length; for(i = 0; i < catlength; i++) { var section = array[i]; var head = document.getElementById(section + '-header'); var cont = section + '-content'; var contdiv = document.getElementById(cont); clearInterval(contdiv.timer); if(head == div && contdiv.style.display == 'none') { contdiv.style.height = '0px'; contdiv.style.display = 'block'; initSlide(cont,1); } else if(contdiv.style.display == 'block') initSlide(cont,-1); } } //--------------------------------------------------------------------------- // Setup the variables and call the slide function function initSlide(id,dir) { var cont = document.getElementById(id); var maxh = cont.maxh; cont.direction = dir; cont.timer = setInterval("slide('" + id + "')", timer); } //--------------------------------------------------------------------------- // Collapse or expand the div by incrementally changing the divs height and opacity function slide(id) { var cont = document.getElementById(id); var maxh = cont.maxh; var currheight = cont.offsetHeight; var dist; if(cont.direction == 1) dist = (Math.round((maxh - currheight) / speed)); else dist = (Math.round(currheight / speed)); if(dist <= 1) dist = 1; cont.style.height = currheight + (dist * cont.direction) + 'px'; cont.style.opacity = currheight / cont.maxh; cont.style.filter = 'alpha(opacity=' + (currheight * 100 / cont.maxh) + ')'; if(currheight < 2 && cont.direction != 1) { cont.style.display = 'none'; clearInterval(cont.timer); } else if(currheight > (maxh - 2) && cont.direction == 1) clearInterval(cont.timer); } //---------------------------------------------------------------------------

Ссылки

* Уроки JS * Примеры AJAX

См.также

* HTML и CSS * PHP