logo search
Vvedenie_v_Veb_programmirovanien_2 / Vvedenie_v_Veb_programmirovanien_2

Примеры на JavaScript

Приветствие в зависимости от времени суток

<html>

<head>

<title>Привет</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script language="JavaScript">

day = new Date();

hour = day.getHours();

if (hour>=5 && hour<12) greeting = "Доброе утро";

else

if (hour>=12 && hour<18) greeting = "Добрый день";

else

if (hour>=18 && hour<24) greeting = "Добрый вечер";

else

if (hour>=0 && hour<5) greeting = "Доброй ночи";

document.write(greeting); </script>

</head>

<body>

</body>

</html>

<!-- пример 32: создание динамического меню после загрузки страницы -->

<html><head>

<style>

.menuContainer {

border: 1px solid #123456;

}

.menuContainer .menuItem {

float: left;

margin: 2px;

padding: 10px;

}

.menuContainer .menuOver {

background-color: #808080;

}

.menuContainer .menuOver a {

color: #800000;

font-weight: bold;

}

.menuContainer .clear {

clear: left;

}

</style>

<script type="text/javascript">

function processMenu() {

var allDiv = document.getElementsByTagName("DIV");

for (var i = 0; i < allDiv.length; i++) {

if (allDiv[i].className == "menuContainer")

processMenuItem(allDiv[i]);

}

}

function processMenuItem(_obj) {

var allChilds = _obj.childNodes;

for (var i = 0; i < allChilds.length; i++) {

if (allChilds[i].className == "menuItem") {

allChilds[i].onmouseover = function() {

this.className += " menuOver";

}

allChilds[i].onmouseout = function() {

this.className =

this.className.replace(" menuOver","");

}

}

}

}

</script>

</head>

<body onload="processMenu();">

<div class="menuContainer">

<div class="menuItem"><a href="#">first</a></div>

<div class="menuItem"><a href="#">second</a></div>

<div class="menuItem"><a href="#">third</a></div>

<div class="menuItem"><a href="#">fourth</a></div>

<div class="clear"></div>

</div>

</body></html>

<!-- пример pr33: валидация формы -->

<script type="text/javascript">

function submitForm(_form) {debugger;

markErrorField(false);

var errMess = "";

if (!_form.elements["login"].value) {

errMess += "Your Login is empty.\n";

markErrorField(_form.elements["login"]);

}

if (!_form.elements["mail"].value) {

errMess += "Your Email is empty\n";

markErrorField(_form.elements["mail"]);

}

if (!_form.elements["pass"].value) {

errMess += "Your Password is empty.\n";

markErrorField(_form.elements["pass"]);

} else if (!_form.elements["confpass"].value) {

errMess +=

"Your Password confirmation is empty.\n";

markErrorField(_form.elements["confpass"]);

} else if

(_form.elements["pass"].value !=

_form.elements["confpass"].value) {

errMess +=

"Your Password confirmation does not equal to your Password.\n";

markErrorField(_form.elements["pass"]);

markErrorField(_form.elements["confpass"]);

}

if (errMess) {

alert(errMess + "");

return false;

}

}

function markErrorField(_element) {

var allLabels =

document.getElementsByTagName("LABEL");

if (_element) {

for (var i = 0; i < allLabels.length; i++) {

if (allLabels[i].htmlFor == _element.id)

allLabels[i].style.color = "red"; }

} else {

for (var i = 0; i < allLabels.length; i++) {

allLabels[i].style.color = "black";

}

}

}

</script>

<form onsubmit="return submitForm(this);">

<table>

<tr>

<td><label for="login">Your Login</label></td>

<td><input type="text" name="login" id="login" /></td>

</tr>

<tr>

<td><label for="mail">Your Email</label></td>

<td><input type="text" name="mail" id="mail" /></td>

</tr>

<tr>

<td><label for="pass">Your Password</label></td>

<td><input type="password" name="pass" id="pass" /></td>

</tr>

<tr>

<td><label for="confpass">

Confirm Your Password</label></td>

<td><input type="password" name="confpass"

id="confpass" /></td>

</tr>

<tr>

<td colspan="2"><input type="submit"

name="Register" /></td>

</tr>

</table>

</form>

//pr34-Выделение всех чекбоксов (checkbox) в группе

<html>

<head>

<script type="text/javascript">

function checkAll(oForm, cbName, checked)

{

for (var i=0; i < oForm[cbName].length; i++) oForm[cbName][i].checked = checked;

}

</script>

</head>

<body>

<form name="form1" method="post" action="">

<input type="checkbox" name="total" value="checkbox" onClick="checkAll(this.form,'checkbox[]',this.checked)">Отметить все

<br>

<input type="checkbox" name="checkbox[]" value="checkbox">1

<br>

<input type="checkbox" name="checkbox[]" value="checkbox">2

<br>

<input type="checkbox" name="checkbox[]" value="checkbox">3

</form>

</body>

</html>

//pr35- Проверка информации, введенной в форму

<html><head>

<script language="JavaScript">

<!--

var ok1=false

function test(form)

{

if (form.text1.value == "")

{

ok1=false

alert("Введите имя!")

}

else

if ((form.text2.value.indexOf('@', 0)<1) ||(form.text2.value.indexOf('@', 0)==

form.text2.value.length-1))

{

ok1=false

alert("Неправильно введён адрес e-mail")

}

else ok1=true

if(ok1)

{

//..............

alert("Форма заполнена!")

}

}

// -->

</script>

</head>

<body>

<form>

Введите Ваше имя:<br>

<input type="text" name="text1">

<br>

Введите Ваш адрес e-mail:<br>

<input type="text" name="text2">

<br><br>

<input type="button" name="button1" value="Проверка" onClick="test(this.form)">

</form>

</body></html>

//pr36- Анимация элементов страницы – по диагонали.

<html>

<head>

<script>

var dx=1;

var dy=-2;

var timer;

function preloadTime() {

timer=window.setInterval("preloadImg()", 100);

}

function preloadImg() {

animImg.style.pixelTop+=dy;

animImg.style.pixelLeft-= dx;

if (animImg.style.pixelTop + animImg.style.pixelHeight +1 >= document.body.clientHeight) dy=-dy;

if (animImg.style.pixelTop <=0) dy=-dy;

if (animImg.style.pixelLeft + animImg.style.pixelWidth +2 >= document.body.clientWidth) dx=-dx;

if (animImg.style.pixelLeft <=0) dx=-dx;

}

</script>

</head>

<body onLoad="preloadTime()">

<img src="2.gif" id="animImg" style="top:80; left:80; position:absolute; width: 196px; height: 183px;">

</body>

</html>

//pr37- Тип браузера.

<html>

<head>

<script type="text/javascript">

function determineIt() {

if (navigator.appName.indexOf ("Avant")!= -1)

location.href="анимация.html";

else

location.href="inner.html";

}

</script>

</head>

<body onLoad="determineIt()">

</body>

</html>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>Задание №15</title>

<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>

<script type="text/javascript">

function main(){

window.status = decodeURI(window.location.href);

alert("Текущий адрес: " + decodeURI(window.location.href));

}

</script>

</head>

<body>

<button onclick="main()">Получить URL</button>

</body>

</html>

3. Выпадающее меню с помощью css

<html>

<head>

<title>Horizontal Drop Down Menus</title>

<script type="text/javascript">

startList = function() {

if (document.all&&document.getElementById) {

navRoot = document.getElementById("nav");

for (i=0; i<navRoot.childNodes.length; i++) {

node = navRoot.childNodes[i];

if (node.nodeName=="LI") {

node.onmouseover=function() {

this.className+=" over";

}

node.onmouseout=function() {

this.className=this.className.replace(" over", "");

}

}

}

}

}

window.onload=startList;

</script>

<style type="text/css">

body {

font-family:verdana;

font-size:11px;

line-height:normal;

}

ul {

border-bottom:1px solid #ccc;

list-style-image:none;

list-style-position:outside;

list-style-type:none;

margin:0pt;

padding:0pt;

width:150px;

}

ul li {

position:relative;

}

li ul {

display:none;

left:149px;

position:absolute;

top:0pt;

}

ul li a {

background:#fff none repeat scroll 0%;

border-color :#ccc;

border-style:solid;

border-width:1px 1px 0pt;

color: black;

display:block;

padding:5px;

text-decoration:none;

}

* html ul li {

float:left;

height:1%;

}

* html ul li a {

height:1%;

}

ul li a:hover {

background:#fe0 none repeat scroll 0%;

color:red;

}

li ul li a {

padding:2px 5px;

}

li:hover ul, li.over ul {

display:block;

}

</style>

</head>

<body>

<ul id="nav">

<li><a href="#">One</a></li>

<li><a href="#">Two</a>

<ul>

<li><a href="#"> Two One</a></li>

<li><a href="#"> Two Two </a></li>

<li><a href="#"> Two Three</a></li>

</ul>

</li>

<li><a href="#">Three</a>

<ul>

<li><a href="#"> Three One</a></li>

<li><a href="#"> Three Two</a></li>

<li><a href="#"> Three Three </a></li>

<li><a href="#"> Three Four</a></li>

</ul>

</li>

</ul>

</body>

</html>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- :mode=html:collapseFolds=1:indentSize=4:tabSize=4:folding=explicit: -->

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Context menu</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script language='javascript' src='jquery-1.3.2.js'></script>

<script language='javascript' src='jquery.cmenu.js'></script>

<style>

/* page style */

body{

font-family: tahoma, verdana;

font-size: 80%;

}

/* cmenu ubuntu styles*/

.cmenu {

display:none;

position:absolute;

cursor: default;

background: #302f2c;

border: 1px solid #222220;

z-index:100;

}

.cmenu img{

vertical-align:middle;

}

.cmenuItem{

white-space: nowrap;

font-size:11px;

color: #c2c2b7;

height: 20px;

margin-top: -1px;

margin-left: -1px;

border: 1px solid transparent;

}

.cmenuItem .cmenuIcon {

width: 16px;

height: 16px;

margin: 0;

padding: 2px;

float: left;

}

.cmenuItem .cmenuTitle {

float: left;

padding: 2px;

height: 16px;

}

.cmenuItem .submenuBullet {

width: 16px;

height: 16px;

padding: 2px;

float: right;

clear: right;

}

.cmenuItem .hasSubmenu {

background: url(images/submenu_bullet.png) no-repeat 50% 50%;

}

.cmenuItem:hover{

background: url(images/menuitem_hover.png) repeat-x;

color: #fff;

border-color: #5c4842;

}

.cmenuItemWithSub{

background: #336;

color: #fff;

}

.cmenu hr{

width: 100%;

height: 1px;

border-width: 0;

background: #3a3a3a;

padding-left: 3px;

padding-right: 3px;

}

/* sample */

#code,#lt,#rt,#lb,#rb{position: absolute;z-index:1;}

#lt,#lb{left:10px;}

#rt,#rb{right:10px;}

#rb,#lb{bottom:10px;}

#rt,#lt{top:10px;}

#code{top:30px;left:0;right:0;bottom:0;z-index:0;margin-left:200px;}

pre{font-size:12px;}

/* code highlight */

.str{color:red;}

.func{color:blue;}

.comm{color:orange;}

.kwrd{font-weight:bold;}

.str span{color:red;font-weight:normal;}

.comm span{color:orange;font-weight:normal;}

</style>

<script>

/*global jQuery, $, MenuItem, asdasdasd*/

(function ($) {

$.fn.syntax = function () {

return this.each(function () {

var jqCode = $(this);

var code = jqCode.text();

code = code

.replace(/(var|function|typeof|new|return|if|for|in|while|break|do|continue)([^a-z0-9\$_])/gi, '<span class="kwrd">$1<\/span>$2')

.replace(/(\{|\}|\]|\[|\|)/gi, '<span class="kwrd">$1<\/span>')

.replace(/(\/\/[^\n\r]*(\n|\r\n))/g, '<span class="comm">$1<\/span>')

.replace(/('.*?')/g, '<span class="str">$1<\/span>')

.replace(/([a-z\_\$][a-z0-9_]*)\(/gi, '<span class="func">$1<\/span>(')

.replace(/\t/g, ' ');

jqCode.html(code);

});

};

})(jQuery);

$(document).ready(function () {

var def_act = function (x, parent) {

alert(x.caption);

};

/* var asda = [

new MenuItem('Назад', 'arrow_left', function () {history.back();}),

new MenuItem('!Вперед', 'arrow_right', function () {history.forward();}),

new MenuItem('Обновить','arrow_refresh', function () {location.href=location.href;})

]; */

/* var asda = [

['Назад', 'arrow_left', function () {history.back();}],

['!Вперед', 'arrow_right', function () {history.forward();}],

['Обновить','arrow_refresh', function () {location.href=location.href;}]

]; */

var asda = [

['Back', 'arrow_left', function () {

history.back();

}],

['Forward', 'arrow_right', function () {

history.forward();

}],

['Reload page', 'arrow_refresh', function () {

location.href = location.href;

}],

'-',

['Restore closed tab', 'tab', def_act],

['Add page to bookmarks', 'folder_heart', def_act],

['Save as...', 'disk', def_act],

['Send link', 'link', def_act],

'-',

['!Open background image', 'image', def_act],// ! — disabled=true

['Select all', 'shading', def_act],

['Copy', 'page_white_copy', def_act],

['Paste', 'page_white_paste', def_act],

'-',

['Inspect element', 'bug'],

['Select encoding', '', false, function (z) {

z.a = [];

var x = 'utf-8,utf8-y,utf-16,utf-16le,utf-16be,koi8-r,koi8-u,windows-1251'.split(',');

for (var i in x) {

z.a.push(new MenuItem(x[i]));

}

z.type = 'radio';

z.set = function (i) {

asdasdasd = i;

};

z.get = function () {

return typeof asdasdasd === 'string'?asdasdasd:'koi8-r';

};

return true;

}]

];

var table_common = function (item) {

//console.log(item);return;

//location.href = '/db/' + parent.p[parent.p.length-1].cmenu_item.caption + '/' + x.caption;

location.href = '/db/' + item.parent.caption + '/' + item.caption;

}

var table_menu = $.cmenu.get_menu([

['data', 'table', function (mi) {

location.href = '/db/' + mi.parent.parent.caption + '/' +

mi.parent.caption + '/data';

}

],

['!indexes'],['!triggers'],['!constraints']

]);

$('.firefoxmenu').bindMenu(asda);

cb = function (menu) {

menu.async = true;

if (menu.a) {

return menu.a;

}

$.getJSON('/db.json', function (r) {

menu.a = [];

for (var i in r.databases) {

menu.a.push([r.databases[i], 'database', def_act, cb2]);

}

menu.done();

});

};

cb2 = function (menu) {

menu.async = true;

if (menu.a) {

return menu.a;

}

var table = menu.parent_item.caption;

$.getJSON('/db/' + table + '.json', function (r) {

menu.a = [];

for (var i in r.tables) {

menu.a.push([r.tables[i], 'database_table', table_common, table_menu]);

}

menu.done();

});

};

//$('.firefoxmenu').bindMenu(cb);

// my simple syntax hl

$('#code pre').syntax();

});

</script>

</head>

<body>

<span id="lt" class="firefoxmenu">Click for FF3 menu</span>

<span id="rt" class="firefoxmenu">Click for FF3 menu</span>

<span id="lb" class="firefoxmenu">Click for FF3 menu</span>

<span id="rb" class="firefoxmenu">Click for FF3 menu</span>

</body>

</html>