beautify html

This commit is contained in:
Ilya Kantor 2015-03-09 19:02:13 +03:00
parent ecf1478e7e
commit 5342f628da
354 changed files with 13965 additions and 9486 deletions

View file

@ -1,16 +1,17 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
На этой странице есть скрипт с ошибкой. На этой странице есть скрипт с ошибкой.
<script> <script>
lalala
lalala </script>
</script>
</body> </body>
</html> </html>

View file

@ -1,13 +1,16 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script> <script>
alert('Я - JavaScript!'); alert('Я - JavaScript!');
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,18 +1,18 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<script> <script>
var value = prompt('Каково "официальное" название JavaScript?', '');
var value = prompt('Каково "официальное" название JavaScript?', ''); if (value == 'EcmaScript') {
alert('Верно!');
if ( value == 'EcmaScript' ) { } else {
alert('Верно!'); alert('Не знаете? "EcmaScript"!');
} else { }
alert('Не знаете? "EcmaScript"!'); </script>
}
</script>
</body> </body>
</html> </html>

View file

@ -1,18 +1,18 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<script> <script>
var value = prompt('Каково "официальное" название JavaScript?', '');
var value = prompt('Каково "официальное" название JavaScript?', ''); if (value == 'EcmaScript') {
alert('Верно!');
if ( value == 'EcmaScript' ) { } else {
alert('Верно!'); alert('Не знаете? "EcmaScript"!');
} else { }
alert('Не знаете? "EcmaScript"!'); </script>
}
</script>
</body> </body>
</html> </html>

View file

@ -1,23 +1,24 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script> <script>
var value = prompt('Введите число', 0);
var value = prompt('Введите число', 0); if (value > 0) {
alert(1);
if (value > 0) { } else if (value < 0) {
alert(1); alert(-1);
} else if (value < 0) { } else {
alert(-1); alert(0);
} else { }
alert(0); </script>
}
</script>
</body> </body>
</html> </html>

View file

@ -1,11 +1,14 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script src="alert.js"></script> <script src="alert.js"></script>
</body> </body>
</html> </html>

View file

@ -1,8 +1,10 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
</head> </head>
<body> <body>
<script src="pow.js"></script> <script src="pow.js"></script>
@ -12,8 +14,9 @@
<script> <script>
var fiveInCube = pow(5, 3); var fiveInCube = pow(5, 3);
alert( fiveInCube ); alert(fiveInCube);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,8 +1,10 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
</head> </head>
<body> <body>
<script src="pow.js"></script> <script src="pow.js"></script>
@ -12,8 +14,9 @@
<script> <script>
var fiveInCube = pow(5, 3); var fiveInCube = pow(5, 3);
alert( fiveInCube ); alert(fiveInCube);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,13 +1,18 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -19,6 +24,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -31,6 +36,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -31,6 +36,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -31,6 +36,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -22,13 +27,12 @@
function pow(x, n) { function pow(x, n) {
var result = 1; var result = 1;
for(var i = 0; i < n; i++) { for (var i = 0; i < n; i++) {
result *= x; result *= x;
} }
return result; return result;
} }
</script> </script>
<!-- в этом скрипте находятся спеки --> <!-- в этом скрипте находятся спеки -->
@ -38,6 +42,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -22,13 +27,12 @@
function pow(x, n) { function pow(x, n) {
var result = 1; var result = 1;
for(var i = 0; i < n; i++) { for (var i = 0; i < n; i++) {
result *= x; result *= x;
} }
return result; return result;
} }
</script> </script>
<!-- в этом скрипте находятся спеки --> <!-- в этом скрипте находятся спеки -->
@ -38,6 +42,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -22,10 +27,10 @@
function pow(x, n) { function pow(x, n) {
if (n < 0) return NaN; if (n < 0) return NaN;
if (Math.round(n) != n) return NaN; if (Math.round(n) != n) return NaN;
if (n == 0 && x ==0) return NaN; if (n == 0 && x == 0) return NaN;
var result = 1; var result = 1;
for(var i=0; i<n; i++) { for (var i = 0; i < n; i++) {
result *= x; result *= x;
} }
return result; return result;
@ -39,6 +44,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -31,6 +36,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -21,7 +26,7 @@
<script> <script>
function pow(x, n) { function pow(x, n) {
var result = 1; var result = 1;
for(var i=0; i<n; i++) { for (var i = 0; i < n; i++) {
result *= x; result *= x;
} }
return result; return result;
@ -35,6 +40,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
@ -8,12 +9,16 @@
<!-- подключаем библиотеку Mocha --> <!-- подключаем библиотеку Mocha -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!-- настраиваем Mocha: предстоит BDD-тестирование --> <!-- настраиваем Mocha: предстоит BDD-тестирование -->
<script> mocha.setup('bdd'); </script> <script>
mocha.setup('bdd');
</script>
<!-- подключаем chai --> <!-- подключаем chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!-- в chai есть много всего, выносим assert в глобальную область --> <!-- в chai есть много всего, выносим assert в глобальную область -->
<script> var assert = chai.assert; </script> <script>
var assert = chai.assert;
</script>
</head> </head>
<body> <body>
@ -21,7 +26,7 @@
<script> <script>
function pow(x, n) { function pow(x, n) {
var result = 1; var result = 1;
for(var i=0; i<n; i++) { for (var i = 0; i < n; i++) {
result *= x; result *= x;
} }
return result; return result;
@ -35,6 +40,9 @@
<div id="mocha"></div> <div id="mocha"></div>
<!-- запустить тесты! --> <!-- запустить тесты! -->
<script> mocha.run(); </script> <script>
mocha.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<script> <script>
@ -7,14 +8,16 @@
</script> </script>
<script src="hello.js"></script> <script src="hello.js"></script>
</head> </head>
<body> <body>
<button>Кнопка</button> <button>Кнопка</button>
<script> <script>
alert(message); alert(message);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<script> <script>
@ -7,14 +8,16 @@
</script> </script>
<script src="hello.js"></script> <script src="hello.js"></script>
</head> </head>
<body> <body>
<button>Кнопка</button> <button>Кнопка</button>
<script> <script>
alert(message); alert(message);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,49 +1,59 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> div { height: 18px; margin: 1px; background-color:green; } </style> <style>
div {
height: 18px;
margin: 1px;
background-color: green;
}
</style>
</head> </head>
<body> <body>
<input type="button" id="start" value="Старт"> <input type="button" id="start" value="Старт">
<input type="button" id="stop" value="Стоп" disabled> <input type="button" id="stop" value="Стоп" disabled>
<script> <script>
for (var i=0; i<=20; i+=2) { for (var i = 0; i <= 20; i += 2) {
document.write('<div>'+i+'</div>'); document.write('<div>' + i + '</div>');
} }
var startButton = document.getElementById('start'); var startButton = document.getElementById('start');
var stopButton = document.getElementById('stop'); var stopButton = document.getElementById('stop');
var timers = []; var timers = [];
stopButton.onclick = function() { stopButton.onclick = function() {
startButton.disabled = false; startButton.disabled = false;
stopButton.disabled = true; stopButton.disabled = true;
for(var i=0; i<timers.length; i++) clearInterval(timers[i]); for (var i = 0; i < timers.length; i++) clearInterval(timers[i]);
timers = []; timers = [];
} }
startButton.onclick = function() { startButton.onclick = function() {
startButton.disabled = true; startButton.disabled = true;
stopButton.disabled = false; stopButton.disabled = false;
var divs = document.getElementsByTagName('div'); var divs = document.getElementsByTagName('div');
for (var i=0; i<divs.length; i++) { for (var i = 0; i < divs.length; i++) {
animateDiv(divs, i); animateDiv(divs, i);
} }
} }
function animateDiv(divs, i) { function animateDiv(divs, i) {
var div = divs[i], speed = div.innerHTML; var div = divs[i],
timers[i] = setInterval(function() { speed = div.innerHTML;
div.style.width = (parseInt(div.style.width||0) + 2) % 400 + 'px' timers[i] = setInterval(function() {
}, speed); div.style.width = (parseInt(div.style.width || 0) + 2) % 400 + 'px'
} }, speed);
</script> }
</script>
</body> </body>
</html> </html>

View file

@ -1,48 +1,51 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
</head> </head>
<body> <body>
<script> <script>
function Machine(power) { function Machine(power) {
this._enabled = false; this._enabled = false;
this.enable = function() { this.enable = function() {
this._enabled = true; this._enabled = true;
}; };
this.disable = function() { this.disable = function() {
this._enabled = false; this._enabled = false;
}; };
}
function CoffeeMachine(power) {
Machine.apply(this, arguments);
var waterAmount = 0;
this.setWaterAmount = function(amount) {
waterAmount = amount;
};
function onReady() {
alert('Кофе готов!');
}
this.run = function() {
if (!this._enabled) {
throw new Error("Кофеварка выключена");
} }
setTimeout(onReady, 1000);
};
} function CoffeeMachine(power) {
Machine.apply(this, arguments);
var coffeeMachine = new CoffeeMachine(10000); var waterAmount = 0;
coffeeMachine.run();
</script> this.setWaterAmount = function(amount) {
waterAmount = amount;
};
function onReady() {
alert('Кофе готов!');
}
this.run = function() {
if (!this._enabled) {
throw new Error("Кофеварка выключена");
}
setTimeout(onReady, 1000);
};
}
var coffeeMachine = new CoffeeMachine(10000);
coffeeMachine.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,42 +1,45 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
</head> </head>
<body> <body>
<script> <script>
function Machine(power) { function Machine(power) {
this._enabled = false; this._enabled = false;
this.enable = function() { this.enable = function() {
this._enabled = true; this._enabled = true;
}; };
this.disable = function() { this.disable = function() {
this._enabled = false; this._enabled = false;
}; };
} }
function CoffeeMachine(power) { function CoffeeMachine(power) {
Machine.apply(this, arguments); Machine.apply(this, arguments);
var waterAmount = 0; var waterAmount = 0;
this.setWaterAmount = function(amount) { this.setWaterAmount = function(amount) {
waterAmount = amount; waterAmount = amount;
}; };
function onReady() { function onReady() {
alert('Кофе готово!'); alert('Кофе готово!');
} }
this.run = function() { this.run = function() {
setTimeout(onReady, 1000); setTimeout(onReady, 1000);
}; };
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,55 +1,58 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
</head> </head>
<body> <body>
<script> <script>
function Machine(power) { function Machine(power) {
this._enabled = false; this._enabled = false;
this.enable = function() { this.enable = function() {
this._enabled = true; this._enabled = true;
}; };
this.disable = function() { this.disable = function() {
this._enabled = false; this._enabled = false;
}; };
}
function CoffeeMachine(power) {
Machine.apply(this, arguments);
var waterAmount = 0;
var timerId;
this.setWaterAmount = function(amount) {
waterAmount = amount;
};
function onReady() {
alert('Кофе готов!');
}
var parentDisable = this.disable;
this.disable = function() {
parentDisable.call(this);
clearTimeout(timerId);
}
this.run = function() {
if (!this._enabled) {
throw new Error("Кофеварка выключена");
} }
timerId = setTimeout(onReady, 1000);
};
} function CoffeeMachine(power) {
Machine.apply(this, arguments);
var coffeeMachine = new CoffeeMachine(10000); var waterAmount = 0;
coffeeMachine.run(); var timerId;
</script>
this.setWaterAmount = function(amount) {
waterAmount = amount;
};
function onReady() {
alert('Кофе готов!');
}
var parentDisable = this.disable;
this.disable = function() {
parentDisable.call(this);
clearTimeout(timerId);
}
this.run = function() {
if (!this._enabled) {
throw new Error("Кофеварка выключена");
}
timerId = setTimeout(onReady, 1000);
};
}
var coffeeMachine = new CoffeeMachine(10000);
coffeeMachine.run();
</script>
</body> </body>
</html> </html>

View file

@ -1,18 +1,21 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<title>Часики в консоли</title> <title>Часики в консоли</title>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script src="clock.js"></script> <script src="clock.js"></script>
<script> <script>
var clock = new Clock({ var clock = new Clock({
template: 'h:m:s' template: 'h:m:s'
}); });
clock.start(); clock.start();
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,18 +1,21 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<title>Часики в консоли</title> <title>Часики в консоли</title>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script src="clock.js"></script> <script src="clock.js"></script>
<script> <script>
var clock = new Clock({ var clock = new Clock({
template: 'h:m:s' template: 'h:m:s'
}); });
clock.start(); clock.start();
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,23 +1,26 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<title>Часики в консоли</title> <title>Часики в консоли</title>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script src="clock.js"></script> <script src="clock.js"></script>
<script src="extended-clock.js"></script> <script src="extended-clock.js"></script>
<script> <script>
var lowResolutionClock = new ExtendedClock({ var lowResolutionClock = new ExtendedClock({
template: 'h:m:s', template: 'h:m:s',
precision: 10000 precision: 10000
}); });
lowResolutionClock.start(); lowResolutionClock.start();
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,21 +1,23 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<title>Часики в консоли</title> <title>Часики в консоли</title>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<!-- исходные часы, от них нужно унаследовать --> <!-- исходные часы, от них нужно унаследовать -->
<script src="clock.js"></script> <script src="clock.js"></script>
<script> <script>
var clock = new Clock({ var clock = new Clock({
template: 'h:m:s' template: 'h:m:s'
}); });
clock.start(); clock.start();
/* ... ваш код для ExtendedClock */ /* ... ваш код для ExtendedClock */
/* /*
Надо: часы, которые тикают раз в 10 секунд (точность 10000) Надо: часы, которые тикают раз в 10 секунд (точность 10000)
@ -26,8 +28,8 @@
lowResolutionClock.start(); lowResolutionClock.start();
*/ */
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,67 +1,64 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script src="menu.js"></script> <script src="menu.js"></script>
<script> <script>
function AnimatingMenu() {
function AnimatingMenu() { Menu.apply(this, arguments);
Menu.apply(this, arguments);
}
AnimatingMenu.prototype = Object.create(Menu.prototype);
AnimatingMenu.prototype.STATE_ANIMATING = 2;
AnimatingMenu.prototype.open = function() {
var self = this;
this._state = this.STATE_ANIMATING;
this._timer = setTimeout(function() {
Menu.prototype.open.call(self);
}, 1000);
};
AnimatingMenu.prototype.close = function() {
clearTimeout(this._timer);
Menu.prototype.close.apply(this);
};
AnimatingMenu.prototype._stateAsString = function() {
switch(this._state) {
case this.STATE_ANIMATING:
return 'анимация';
default:
return Menu.prototype._stateAsString.call(this);
} }
};
// тест, использование.. AnimatingMenu.prototype = Object.create(Menu.prototype);
var menu = new AnimatingMenu();
menu.showState(); // закрыто AnimatingMenu.prototype.STATE_ANIMATING = 2;
menu.open(); AnimatingMenu.prototype.open = function() {
menu.showState(); // анимация var self = this;
setTimeout(function() { // через 1 секунду this._state = this.STATE_ANIMATING;
menu.showState(); // открыто
this._timer = setTimeout(function() {
Menu.prototype.open.call(self);
}, 1000);
};
AnimatingMenu.prototype.close = function() {
clearTimeout(this._timer);
Menu.prototype.close.apply(this);
};
AnimatingMenu.prototype._stateAsString = function() {
switch (this._state) {
case this.STATE_ANIMATING:
return 'анимация';
default:
return Menu.prototype._stateAsString.call(this);
}
};
// тест, использование..
var menu = new AnimatingMenu();
menu.close();
menu.showState(); // закрыто menu.showState(); // закрыто
}, 1000);
menu.open();
menu.showState(); // анимация
setTimeout(function() { // через 1 секунду
menu.showState(); // открыто
menu.close();
menu.showState(); // закрыто
</script> }, 1000);
</script>
</body> </body>
</html> </html>

View file

@ -1,33 +1,33 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<script src="menu.js"></script> <script src="menu.js"></script>
<script> <script>
var AnimatingMenu = Menu; // замените на ваш код для AnimatingMenu
var AnimatingMenu = Menu; // замените на ваш код для AnimatingMenu // использование..
// использование.. var menu = new AnimatingMenu();
var menu = new AnimatingMenu(); menu.showState(); // закрыто
menu.showState(); // закрыто menu.open();
menu.showState(); // анимация
menu.open(); setTimeout(function() {
menu.showState(); // анимация menu.showState(); // открыто
setTimeout(function() { menu.close();
menu.showState(); // открыто menu.showState(); // закрыто (закрытие без анимации)
}, 1000);
menu.close(); </script>
menu.showState(); // закрыто (закрытие без анимации)
}, 1000);
</script>
</body> </body>
</html> </html>

View file

@ -1,45 +1,45 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="setImmediate.js"></script> <script src="setImmediate.js"></script>
</head> </head>
<body> <body>
<button onclick="testTimeout()">testTimeout</button> <button onclick="testTimeout()">testTimeout</button>
<button onclick="testImmediate()">testImmediate</button> <button onclick="testImmediate()">testImmediate</button>
<script> <script>
function testTimeout() {
var start = new Date();
var i = 0;
setTimeout(function go() {
i++;
if (i == 100) {
alert(new Date - start);
} else {
setTimeout(go, 0);
}
}, 0);
}
function testTimeout() { function testImmediate() {
var start = new Date(); var start = new Date();
var i = 0; var i = 0;
setTimeout(function go() { setImmediate(function go() {
i++; i++;
if (i == 100) { if (i == 100) {
alert(new Date - start); alert(new Date - start);
} else { } else {
setTimeout(go, 0); setImmediate(go);
} }
}, 0); });
} }
</script>
function testImmediate() {
var start = new Date();
var i = 0;
setImmediate(function go() {
i++;
if (i == 100) {
alert(new Date - start);
} else {
setImmediate(go);
}
});
}
</script>
</body> </body>
</html> </html>

View file

@ -1,37 +1,40 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="ex2" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;"> <div id="ex2" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;">
<h2 style="color:#333; margin:0; padding:0 0 7px 0; font:bold 15px Arial;">Соз|даем Range-объект</h2> <h2 style="color:#333; margin:0; padding:0 0 7px 0; font:bold 15px Arial;">Соз|даем Range-объект</h2>
<p style="color:#333; margin:0; font:13px Arial;">От третье|го символа заголовка до десятого символа это абзаца.</p> <p style="color:#333; margin:0; font:13px Arial;">От третье|го символа заголовка до десятого символа это абзаца.</p>
</div> </div>
<button onclick="alert(domRangeCreate())">Создать Range и вывести его текст</button> <button onclick="alert(domRangeCreate())">Создать Range и вывести его текст</button>
<script> <script>
function domRangeCreate() { function domRangeCreate() {
// Найдем корневой контейнер // Найдем корневой контейнер
var root = document.getElementById('ex2'); var root = document.getElementById('ex2');
// Найдем контейнеры граничных точек (в данном случае тестовые) // Найдем контейнеры граничных точек (в данном случае тестовые)
var start = root.getElementsByTagName('h2')[0].firstChild; var start = root.getElementsByTagName('h2')[0].firstChild;
var end = root.getElementsByTagName('p')[0].firstChild; var end = root.getElementsByTagName('p')[0].firstChild;
if (document.createRange) { if (document.createRange) {
// Создаем Range // Создаем Range
var rng = document.createRange(); var rng = document.createRange();
// Задаем верхнюю граничную точку, передав контейнер и смещение // Задаем верхнюю граничную точку, передав контейнер и смещение
rng.setStart( start, 3 ); rng.setStart(start, 3);
// Аналогично для нижней границы // Аналогично для нижней границы
rng.setEnd( end, 10 ); rng.setEnd(end, 10);
// Теперь мы можем вернуть текст, который содержится в полученной области // Теперь мы можем вернуть текст, который содержится в полученной области
return rng.toString(); return rng.toString();
} else { } else {
return 'Вероятно, у вас IE8-, смотрите реализацию TextRange ниже'; return 'Вероятно, у вас IE8-, смотрите реализацию TextRange ниже';
} }
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,34 +1,37 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="ex3" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;"> <div id="ex3" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;">
Найдем в этом тексте слово "бабуля" и подсветим его синим фоном Найдем в этом тексте слово "бабуля" и подсветим его синим фоном
</div> </div>
<div> <div>
<input onclick="domRangehighlight('бабуля'); this.style.display = 'none';" type="button" value="Найти!"> <input onclick="domRangehighlight('бабуля'); this.style.display = 'none';" type="button" value="Найти!">
</div> </div>
<script> <script>
function domRangehighlight( text ) { function domRangehighlight(text) {
var root = document.getElementById('ex3').firstChild; var root = document.getElementById('ex3').firstChild;
var content = root.nodeValue; var content = root.nodeValue;
if ( ~content.indexOf( text ) ) { if (~content.indexOf(text)) {
if ( document.createRange ) { if (document.createRange) {
var rng = document.createRange(); var rng = document.createRange();
rng.setStart( root, content.indexOf( text ) ); rng.setStart(root, content.indexOf(text));
rng.setEnd( root, content.indexOf( text ) + text.length ); rng.setEnd(root, content.indexOf(text) + text.length);
var highlightDiv = document.createElement('span'); var highlightDiv = document.createElement('span');
highlightDiv.style.backgroundColor = 'blue'; highlightDiv.style.backgroundColor = 'blue';
rng.surroundContents( highlightDiv ); rng.surroundContents(highlightDiv);
} else } else
alert('Вероятно, у вас IE8-, смотрите реализацию TextRange ниже'); alert('Вероятно, у вас IE8-, смотрите реализацию TextRange ниже');
} else } else
alert('Совпадений не найдено'); alert('Совпадений не найдено');
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,14 +1,15 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head>
<meta charset="utf-8">
<script src="fixIERangeObject.js"></script>
<script> <head>
<meta charset="utf-8">
<script src="fixIERangeObject.js"></script>
<script>
function test() { function test() {
var range = getRangeObject(); var range = getRangeObject();
if(range) { if (range) {
alert(range); alert(range);
alert(range.startContainer.nodeValue); alert(range.startContainer.nodeValue);
alert(range.startOffset); alert(range.startOffset);
@ -17,11 +18,13 @@
alert('Сначала выделите текст'); alert('Сначала выделите текст');
} }
} }
</script> </script>
</head> </head>
<body>
Выделите текст: <body>
<pre>The quick brown fox jumped over the lazy dog</pre> Выделите текст:
<input type="button" value="Вывести выделение и свойства startContainer, startOffset, endOffset" onclick="test();" /> <pre>The quick brown fox jumped over the lazy dog</pre>
</body> <input type="button" value="Вывести выделение и свойства startContainer, startOffset, endOffset" onclick="test();" />
</body>
</html> </html>

View file

@ -1,32 +1,35 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="ex4" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;"> <div id="ex4" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;">
Найдем в этом тексте слово "бабуля" и подсветим его синим фоном Найдем в этом тексте слово "бабуля" и подсветим его синим фоном
</div> </div>
<div> <div>
<input onclick="ieTextRangeHighlight('бабуля'); this.style.display = 'none';" type="button" value="Найти!"> <input onclick="ieTextRangeHighlight('бабуля'); this.style.display = 'none';" type="button" value="Найти!">
</div> </div>
<script> <script>
function ieTextRangeHighlight(text) { function ieTextRangeHighlight(text) {
var root = document.getElementById('ex4'); var root = document.getElementById('ex4');
var content = root.firstChild.nodeValue; var content = root.firstChild.nodeValue;
if ( ~content.indexOf(text) ) { if (~content.indexOf(text)) {
if ( document.body.createTextRange ) { if (document.body.createTextRange) {
var rng = document.body.createTextRange(); var rng = document.body.createTextRange();
rng.moveToElementText( root ); rng.moveToElementText(root);
if ( rng.findText( text ) ) if (rng.findText(text))
rng.pasteHTML( '<span style="background:blue;">' + text + '</span>' ); rng.pasteHTML('<span style="background:blue;">' + text + '</span>');
} else } else
alert('Вероятно, у вас не IE, смотрите реализацию Range выше'); alert('Вероятно, у вас не IE, смотрите реализацию Range выше');
} else } else
alert('Совпадений не найдено'); alert('Совпадений не найдено');
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,34 +1,37 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="ex5" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;"> <div id="ex5" style="border:1px dashed #999; color:#666; background:#EEE; padding:2px 5px; margin:10px 0;">
Снова будем выделять <span>бабулю</span>, на этот раз без поиска. Снова будем выделять <span>бабулю</span>, на этот раз без поиска.
</div> </div>
<div> <div>
<input onclick="setSelection()" type="button" value="Выделить бабулю"> <input onclick="setSelection()" type="button" value="Выделить бабулю">
</div> </div>
<script> <script>
function setSelection() { function setSelection() {
var target = document.getElementById('ex5').getElementsByTagName('span')[0]; var target = document.getElementById('ex5').getElementsByTagName('span')[0];
var rng, sel; var rng, sel;
if ( document.createRange ) { if (document.createRange) {
rng = document.createRange(); rng = document.createRange();
rng.selectNode( target ) rng.selectNode(target)
sel = window.getSelection(); sel = window.getSelection();
sel.removeAllRanges(); sel.removeAllRanges();
sel.addRange( rng ); sel.addRange(rng);
} else { } else {
var rng = document.body.createTextRange(); var rng = document.body.createTextRange();
rng.moveToElementText( target ); rng.moveToElementText(target);
rng.select(); rng.select();
} }
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,70 +1,73 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<script src="lib.js"></script> <script src="lib.js"></script>
<script src="DragManager.js"></script> <script src="DragManager.js"></script>
<script src="DragAvatar.js"></script> <script src="DragAvatar.js"></script>
<script src="DragZone.js"></script> <script src="DragZone.js"></script>
<script src="DropTarget.js"></script> <script src="DropTarget.js"></script>
<script src="TreeDragAvatar.js"></script> <script src="TreeDragAvatar.js"></script>
<script src="TreeDragZone.js"></script> <script src="TreeDragZone.js"></script>
<script src="TreeDropTarget.js"></script> <script src="TreeDropTarget.js"></script>
<link rel="stylesheet" type="text/css" href="dragTree.css"> <link rel="stylesheet" type="text/css" href="dragTree.css">
</head> </head>
<body> <body>
Возьмите за любой заголовок и поменяйте ему родителя.<br> Возьмите за любой заголовок и поменяйте ему родителя.
В собственных детей перенести нельзя.<br> <br> В собственных детей перенести нельзя.
Потомки всегда отсортированы по алфавиту. <br> Потомки всегда отсортированы по алфавиту.
<ul id="tree"> <ul id="tree">
<li><span>Древо жизни (сверхмалая часть)</span> <li><span>Древо жизни (сверхмалая часть)</span>
<ul> <ul>
<li><span>Грибы</span> <li><span>Грибы</span>
<ul> <ul>
<li><span>Древесные</span> <li><span>Древесные</span>
<ul> <ul>
<li><span>Чага</span></li> <li><span>Чага</span></li>
</ul> </ul>
</li> </li>
<li><span>Наземные</span> <li><span>Наземные</span>
<ul> <ul>
<li><span>Опята</span></li> <li><span>Опята</span></li>
<li><span>Подосиновики</span></li> <li><span>Подосиновики</span></li>
</ul> </ul>
</li>
</ul>
</li> </li>
<li><span>Животные</span> </ul>
<ul> </li>
<li><span>Земноводные</span> <li><span>Животные</span>
<ul> <ul>
<li><span>Лягушки</span></li> <li><span>Земноводные</span>
<li><span>Саламандры</span></li> <ul>
<li><span>Тритоны</span></li> <li><span>Лягушки</span></li>
</ul> <li><span>Саламандры</span></li>
</li> <li><span>Тритоны</span></li>
<li><span>Млекопитающие</span> </ul>
<ul>
<li><span>Коровы</span></li>
<li><span>Ослы</span></li>
<li><span>Собаки</span></li>
<li><span>Тигры</span></li>
</ul>
</li>
</ul>
</li> </li>
</ul> <li><span>Млекопитающие</span>
<ul>
<li><span>Коровы</span></li>
<li><span>Ослы</span></li>
<li><span>Собаки</span></li>
<li><span>Тигры</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li> </li>
</ul> </ul>
<script> <script>
var tree = document.getElementById('tree'); var tree = document.getElementById('tree');
new TreeDragZone(tree); new TreeDragZone(tree);
new TreeDropTarget(tree); new TreeDropTarget(tree);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,48 +1,57 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8">
<style> <head>
.hour { color: red } <meta charset="utf-8">
.min { color: green } <style>
.sec { color: blue } .hour {
</style> color: red
}
.min {
color: green
}
.sec {
color: blue
}
</style>
</head> </head>
<body> <body>
<div id="clock"> <div id="clock">
<span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span> <span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span>
</div> </div>
<script> <script>
var timerId;
var timerId; function update() {
var clock = document.getElementById('clock');
var date = new Date();
function update() { var hours = date.getHours();
var clock = document.getElementById('clock'); if (hours < 10) hours = '0' + hours;
var date = new Date(); clock.children[0].innerHTML = hours;
var hours = date.getHours(); var minutes = date.getMinutes();
if (hours < 10) hours = '0'+hours; if (minutes < 10) minutes = '0' + minutes;
clock.children[0].innerHTML = hours; clock.children[1].innerHTML = minutes;
var minutes = date.getMinutes(); var seconds = date.getSeconds();
if (minutes < 10) minutes = '0'+minutes; if (seconds < 10) seconds = '0' + seconds;
clock.children[1].innerHTML = minutes; clock.children[2].innerHTML = seconds;
}
var seconds = date.getSeconds(); function clockStart() {
if (seconds < 10) seconds = '0'+seconds; setInterval(update, 1000);
clock.children[2].innerHTML = seconds; update(); // <-- начать тут же, не ждать 1 секунду пока setInterval сработает
} }
function clockStart() { clockStart();
setInterval(update, 1000); </script>
update(); // <-- начать тут же, не ждать 1 секунду пока setInterval сработает
}
clockStart();
</script>
</body> </body>
</html> </html>

View file

@ -1,11 +1,13 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<body> <body>
<input type="button" onclick="clockStart()" value="Start"> <input type="button" onclick="clockStart()" value="Start">
<input type="button" onclick="clockStop()" value="Stop"> <input type="button" onclick="clockStop()" value="Stop">
</body> </body>
</html> </html>

View file

@ -1,27 +1,30 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<h1>Создание списка</h1> <h1>Создание списка</h1>
<script> <script>
var ul = document.createElement('ul'); var ul = document.createElement('ul');
document.body.appendChild(ul); document.body.appendChild(ul);
while (true) { while (true) {
var data = prompt("Введите текст для пункта списка", ""); var data = prompt("Введите текст для пункта списка", "");
if (!data) { if (!data) {
break; break;
}
var li = document.createElement('li');
li.appendChild(document.createTextNode(data));
ul.appendChild(li);
} }
</script>
var li = document.createElement('li');
li.appendChild(document.createTextNode(data));
ul.appendChild(li);
}
</script>
</body> </body>
</html> </html>

View file

@ -1,67 +1,70 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="container"></div> <div id="container"></div>
<script> <script>
var data = { var data = {
"Рыбы":{ "Рыбы": {
"Форель":{}, "Форель": {},
"Щука":{} "Щука": {}
},
"Деревья":{
"Хвойные":{
"Лиственница":{},
"Ель":{}
}, },
"Цветковые":{
"Берёза":{}, "Деревья": {
"Тополь":{} "Хвойные": {
"Лиственница": {},
"Ель": {}
},
"Цветковые": {
"Берёза": {},
"Тополь": {}
}
}
};
function createTree(container, obj) {
container.appendChild(createTreeDom(obj));
}
function createTreeDom(obj) {
// если нет детей, то рекурсивный вызов ничего не возвращает
// так что вложенный UL не будет создан
if (isObjectEmpty(obj)) return;
var ul = document.createElement('ul');
for (var key in obj) {
var li = document.createElement('li');
li.innerHTML = key;
var childrenUl = createTreeDom(obj[key]);
if (childrenUl) li.appendChild(childrenUl);
ul.appendChild(li);
} }
} return ul;
};
function createTree(container, obj) {
container.appendChild( createTreeDom(obj) );
}
function createTreeDom(obj) {
// если нет детей, то рекурсивный вызов ничего не возвращает
// так что вложенный UL не будет создан
if (isObjectEmpty(obj)) return;
var ul = document.createElement('ul');
for (var key in obj) {
var li = document.createElement('li');
li.innerHTML = key;
var childrenUl = createTreeDom(obj[key]);
if (childrenUl) li.appendChild(childrenUl);
ul.appendChild(li);
} }
return ul;
}
function isObjectEmpty(obj) {
function isObjectEmpty(obj) { for (var key in obj) {
for (var key in obj) { return false;
return false; }
return true;
} }
return true;
}
var container = document.getElementById('container'); var container = document.getElementById('container');
createTree(container, data); createTree(container, data);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,49 +1,52 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="container"></div> <div id="container"></div>
<script> <script>
var data = { var data = {
"Рыбы":{ "Рыбы": {
"Форель":{}, "Форель": {},
"Щука":{} "Щука": {}
},
"Деревья":{
"Хвойные":{
"Лиственница":{},
"Ель":{}
}, },
"Цветковые":{
"Берёза":{}, "Деревья": {
"Тополь":{} "Хвойные": {
"Лиственница": {},
"Ель": {}
},
"Цветковые": {
"Берёза": {},
"Тополь": {}
}
} }
};
function createTree(container, obj) {
container.innerHTML = createTreeText(obj);
} }
};
function createTree(container, obj) { function createTreeText(obj) { // отдельная рекурсивная функция
container.innerHTML = createTreeText(obj); var li = '';
} for (var key in obj) {
li += '<li>' + key + createTreeText(obj[key]) + '</li>';
function createTreeText(obj) { // отдельная рекурсивная функция }
var li = ''; if (li) {
for (var key in obj) { var ul = '<ul>' + li + '</ul>'
li += '<li>' + key + createTreeText(obj[key]) + '</li>'; }
return ul || '';
} }
if (li) {
var ul = '<ul>' + li + '</ul>'
}
return ul || '';
}
var container = document.getElementById('container'); var container = document.getElementById('container');
createTree(container, data); createTree(container, data);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,13 +1,15 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="tree"></div> <div id="tree"></div>
<!-- Результат должен быть таким: <!-- Результат должен быть таким:
<div id="tree"> <div id="tree">
<ul> <ul>
<li>Рыбы <li>Рыбы
@ -36,29 +38,30 @@
</div> </div>
--> -->
<script> <script>
var data = { var data = {
"Рыбы":{ "Рыбы": {
"Форель":{}, "Форель": {},
"Щука":{} "Щука": {}
},
"Деревья":{
"Хвойные":{
"Лиственница":{},
"Ель":{}
}, },
"Цветковые":{
"Берёза":{}, "Деревья": {
"Тополь":{} "Хвойные": {
"Лиственница": {},
"Ель": {}
},
"Цветковые": {
"Берёза": {},
"Тополь": {}
}
} }
} };
};
/* ваш код */ /* ваш код */
createTree(document.getElementById('tree'), data); createTree(document.getElementById('tree'), data);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,59 +1,64 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<ul> <ul>
<li>Животные <li>Животные
<ul> <ul>
<li>Млекопитающие <li>Млекопитающие
<ul> <ul>
<li>Коровы</li> <li>Коровы</li>
<li>Ослы</li> <li>Ослы</li>
<li>Собаки</li> <li>Собаки</li>
<li>Тигры</li> <li>Тигры</li>
</ul> </ul>
</li> </li>
<li>Другие <li>Другие
<ul> <ul>
<li>Змеи</li> <li>Змеи</li>
<li>Птицы</li> <li>Птицы</li>
<li>Ящерицы</li> <li>Ящерицы</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
<li>Рыбы <li>Рыбы
<ul> <ul>
<li>Аквариумные <li>Аквариумные
<ul> <ul>
<li>Гуппи</li> <li>Гуппи</li>
<li>Скалярии</li> <li>Скалярии</li>
</ul> </ul>
</li> </li>
<li>Морские <li>Морские
<ul> <ul>
<li>Морская форель</li> <li>Морская форель</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
</ul> </ul>
<script> <script>
var lis = document.getElementsByTagName('li'); var lis = document.getElementsByTagName('li');
for(i=0; i<lis.length; i++) { for (i = 0; i < lis.length; i++) {
// получить количество детей // получить количество детей
var childCount = lis[i].getElementsByTagName('li').length; var childCount = lis[i].getElementsByTagName('li').length;
if (!childCount) continue; if (!childCount) continue;
// добавить кол-во детей к текстовому узлу // добавить кол-во детей к текстовому узлу
lis[i].firstChild.data += ' ['+childCount+']'; lis[i].firstChild.data += ' [' + childCount + ']';
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,49 +1,54 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<ul> <ul>
<li>Животные <li>Животные
<ul> <ul>
<li>Млекопитающие <li>Млекопитающие
<ul> <ul>
<li>Коровы</li> <li>Коровы</li>
<li>Ослы</li> <li>Ослы</li>
<li>Собаки</li> <li>Собаки</li>
<li>Тигры</li> <li>Тигры</li>
</ul> </ul>
</li> </li>
<li>Другие <li>Другие
<ul> <ul>
<li>Змеи</li> <li>Змеи</li>
<li>Птицы</li> <li>Птицы</li>
<li>Ящерицы</li> <li>Ящерицы</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
<li>Рыбы <li>Рыбы
<ul> <ul>
<li>Аквариумные <li>Аквариумные
<ul> <ul>
<li>Гуппи</li> <li>Гуппи</li>
<li>Скалярии</li> <li>Скалярии</li>
</ul> </ul>
</li> </li>
<li>Морские <li>Морские
<ul> <ul>
<li>Морская форель</li> <li>Морская форель</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
</ul> </ul>
<script> <script>
// .. ваш код .. // .. ваш код ..
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,80 +1,84 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<style> <style>
table { table {
border-collapse: collapse; border-collapse: collapse;
} }
td, th { td,
border: 1px solid black; th {
padding: 3px; border: 1px solid black;
text-align: center; padding: 3px;
} text-align: center;
}
th { th {
font-weight: bold; font-weight: bold;
background-color: #E6E6E6; background-color: #E6E6E6;
} }
</style> </style>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="calendar"></div> <div id="calendar"></div>
<script> <script>
function createCalendar(id, year, month) { function createCalendar(id, year, month) {
var elem = document.getElementById(id); var elem = document.getElementById(id);
var mon = month - 1; // месяцы в JS идут от 0 до 11, а не от 1 до 12 var mon = month - 1; // месяцы в JS идут от 0 до 11, а не от 1 до 12
var d = new Date(year, mon); var d = new Date(year, mon);
var table = '<table><tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th>сб</th><th>вс</th></tr><tr>'; var table = '<table><tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th>сб</th><th>вс</th></tr><tr>';
// заполнить первый ряд от понедельника // заполнить первый ряд от понедельника
// и до дня, с которого начинается месяц // и до дня, с которого начинается месяц
// * * * | 1 2 3 4 // * * * | 1 2 3 4
for (var i=0; i<getDay(d); i++) { for (var i = 0; i < getDay(d); i++) {
table += '<td></td>'; table += '<td></td>';
} }
// ячейки календаря с датами // ячейки календаря с датами
while(d.getMonth() == mon) { while (d.getMonth() == mon) {
table += '<td>'+d.getDate()+'</td>'; table += '<td>' + d.getDate() + '</td>';
if (getDay(d) % 7 == 6) { // вс, последний день - перевод строки if (getDay(d) % 7 == 6) { // вс, последний день - перевод строки
table += '</tr><tr>'; table += '</tr><tr>';
}
d.setDate(d.getDate() + 1);
}
// добить таблицу пустыми ячейками, если нужно
if (getDay(d) != 0) {
for (var i = getDay(d); i < 7; i++) {
table += '<td></td>';
}
}
// закрыть таблицу
table += '</tr></table>';
// только одно присваивание innerHTML
elem.innerHTML = table;
} }
d.setDate(d.getDate()+1); function getDay(date) { // получить номер дня недели, от 0(пн) до 6(вс)
} var day = date.getDay();
if (day == 0) day = 7;
// добить таблицу пустыми ячейками, если нужно return day - 1;
if (getDay(d) != 0) {
for (var i=getDay(d); i<7; i++) {
table += '<td></td>';
} }
}
// закрыть таблицу
table += '</tr></table>';
// только одно присваивание innerHTML
elem.innerHTML = table;
}
function getDay(date) { // получить номер дня недели, от 0(пн) до 6(вс)
var day = date.getDay();
if (day == 0) day = 7;
return day - 1;
}
createCalendar("calendar", 2012, 9) createCalendar("calendar", 2012, 9)
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,39 +1,41 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<style> <style>
table { table {
border-collapse: collapse; border-collapse: collapse;
} }
td, th { td,
border: 1px solid black; th {
padding: 3px; border: 1px solid black;
text-align: center; padding: 3px;
} text-align: center;
}
th { th {
font-weight: bold; font-weight: bold;
background-color: #E6E6E6; background-color: #E6E6E6;
} }
</style> </style>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="calendar"></div> <div id="calendar"></div>
<script> <script>
function createCalendar(id, year, month) {
var elem = document.getElementById(id)
function createCalendar(id, year, month) { // ... ваш код, который генерирует в elem календарь
var elem = document.getElementById(id) }
// ... ваш код, который генерирует в elem календарь createCalendar('calendar', 2011, 1)
} </script>
createCalendar('calendar', 2011, 1)
</script>
</body> </body>
</html> </html>

File diff suppressed because one or more lines are too long

View file

@ -1,20 +1,23 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
</head> </head>
<body> <body>
Вставляются 100 элементов LI в пустой UL. Вставляются 100 элементов LI в пустой UL.
<input type="button" onclick="alert(bench(DocumentFragmentTest.insertPlain,200))" value="Замерить время на обычную вставку"/> <input type="button" onclick="alert(bench(DocumentFragmentTest.insertPlain,200))" value="Замерить время на обычную вставку" />
<input type="button" onclick="alert(bench(DocumentFragmentTest.insertDocumentFragment,200))" value="Замерить время на вставку через DocumentFragment"> <input type="button" onclick="alert(bench(DocumentFragmentTest.insertDocumentFragment,200))" value="Замерить время на вставку через DocumentFragment">
<ul id="bench-list"></ul> <ul id="bench-list"></ul>
<script src="bench.js"></script> <script src="bench.js"></script>
<script src="documentfragment-bench.js"></script> <script src="documentfragment-bench.js"></script>
</body> </body>
</html> </html>

View file

@ -1,37 +1,40 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<div> <div>
Кнопка: Кнопка:
<!-- создайте элемент и расположите его тут --> <!-- создайте элемент и расположите его тут -->
</div> </div>
<script> <script>
var a = document.createElement('a'); var a = document.createElement('a');
a.className = 'button'; a.className = 'button';
a.appendChild(document.createTextNode('Нажми меня')); a.appendChild(document.createTextNode('Нажми меня'));
a.href = '/'; a.href = '/';
var s = a.style var s = a.style
s.MozBorderRadius = s.WebkitBorderRadius = s.borderRadius = '8px'; s.MozBorderRadius = s.WebkitBorderRadius = s.borderRadius = '8px';
s.border = '2px groove green'; s.border = '2px groove green';
s.display = 'block'; s.display = 'block';
s.height = '30px'; s.height = '30px';
s.lineHeight = '30px'; s.lineHeight = '30px';
s.width = '100px'; s.width = '100px';
s.textDecoration = 'none'; s.textDecoration = 'none';
s.textAlign = 'center'; s.textAlign = 'center';
s.color = 'red'; s.color = 'red';
s.fontWeight = 'bold'; s.fontWeight = 'bold';
var div = document.body.children[0]; var div = document.body.children[0];
div.appendChild(a); div.appendChild(a);
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,17 +1,22 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<div> <div>
Кнопка: Кнопка:
<!-- создайте элемент и расположите его тут --> <!-- создайте элемент и расположите его тут -->
</div> </div>
<script> <script>
// .. ваш код // .. ваш код
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,15 +1,19 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
</head> </head>
<body> <body>
<h2>Уведомление</h2> <h2>Уведомление</h2>
<p> <p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum aspernatur quam ex eaque inventore quod voluptatem adipisci omnis nemo nulla fugit iste numquam ducimus cumque minima porro ea quidem maxime necessitatibus beatae labore soluta voluptatum magnam consequatur sit laboriosam velit excepturi laborum sequi eos placeat et quia deleniti? Corrupti velit impedit autem et obcaecati fuga debitis nemo ratione iste veniam amet dicta hic ipsam unde cupiditate incidunt aut iure ipsum officiis soluta temporibus. Tempore dicta ullam delectus numquam consectetur quisquam explicabo culpa excepturi placeat quo sequi molestias reprehenderit hic at nemo cumque voluptates quidem repellendus maiores unde earum molestiae ad. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum aspernatur quam ex eaque inventore quod voluptatem adipisci omnis nemo nulla fugit iste numquam ducimus cumque minima porro ea quidem maxime necessitatibus beatae labore soluta voluptatum
magnam consequatur sit laboriosam velit excepturi laborum sequi eos placeat et quia deleniti? Corrupti velit impedit autem et obcaecati fuga debitis nemo ratione iste veniam amet dicta hic ipsam unde cupiditate incidunt aut iure ipsum officiis soluta
temporibus. Tempore dicta ullam delectus numquam consectetur quisquam explicabo culpa excepturi placeat quo sequi molestias reprehenderit hic at nemo cumque voluptates quidem repellendus maiores unde earum molestiae ad.
</p> </p>
<script> <script>
@ -53,9 +57,9 @@
className: "welcome" className: "welcome"
}); });
}, 2000); }, 2000);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,29 +1,33 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
</head> </head>
<body> <body>
<h2>Уведомление</h2> <h2>Уведомление</h2>
<p> <p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum aspernatur quam ex eaque inventore quod voluptatem adipisci omnis nemo nulla fugit iste numquam ducimus cumque minima porro ea quidem maxime necessitatibus beatae labore soluta voluptatum magnam consequatur sit laboriosam velit excepturi laborum sequi eos placeat et quia deleniti? Corrupti velit impedit autem et obcaecati fuga debitis nemo ratione iste veniam amet dicta hic ipsam unde cupiditate incidunt aut iure ipsum officiis soluta temporibus. Tempore dicta ullam delectus numquam consectetur quisquam explicabo culpa excepturi placeat quo sequi molestias reprehenderit hic at nemo cumque voluptates quidem repellendus maiores unde earum molestiae ad. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum aspernatur quam ex eaque inventore quod voluptatem adipisci omnis nemo nulla fugit iste numquam ducimus cumque minima porro ea quidem maxime necessitatibus beatae labore soluta voluptatum
magnam consequatur sit laboriosam velit excepturi laborum sequi eos placeat et quia deleniti? Corrupti velit impedit autem et obcaecati fuga debitis nemo ratione iste veniam amet dicta hic ipsam unde cupiditate incidunt aut iure ipsum officiis soluta
temporibus. Tempore dicta ullam delectus numquam consectetur quisquam explicabo culpa excepturi placeat quo sequi molestias reprehenderit hic at nemo cumque voluptates quidem repellendus maiores unde earum molestiae ad.
</p> </p>
<p>В CSS есть готовый класс notification, который можно ставить уведомлению.</p> <p>В CSS есть готовый класс notification, который можно ставить уведомлению.</p>
<script> <script>
/** /**
* Показывает уведомление, пропадающее через 1.5 сек * Показывает уведомление, пропадающее через 1.5 сек
* *
* @param options.top {number} вертикальный отступ, в px * @param options.top {number} вертикальный отступ, в px
* @param options.right {number} правый отступ, в px * @param options.right {number} правый отступ, в px
* @param options.cssText {string} строка стиля * @param options.cssText {string} строка стиля
* @param options.className {string} CSS-класс * @param options.className {string} CSS-класс
* @param options.html {string} HTML-текст для показа * @param options.html {string} HTML-текст для показа
*/ */
function showNotification(options) { function showNotification(options) {
// ваш код // ваш код
} }
@ -38,9 +42,9 @@
className: "welcome" className: "welcome"
}); });
}, 2000); }, 2000);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,24 +1,30 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<script src="getiecomputedstyle.js"></script> <script src="getiecomputedstyle.js"></script>
</head> </head>
<body> <body>
<style> <style>
#margin-test { margin: 1%; border: 1px solid black; } #margin-test {
</style> margin: 1%;
border: 1px solid black;
}
</style>
<div id="margin-test">Тестовый элемент с margin 1%</div> <div id="margin-test">Тестовый элемент с margin 1%</div>
<script> <script>
var elem = document.getElementById('margin-test'); var elem = document.getElementById('margin-test');
if (!window.getComputedStyle) { // старые IE if (!window.getComputedStyle) { // старые IE
document.write(getIEComputedStyle(elem, 'marginTop')); document.write(getIEComputedStyle(elem, 'marginTop'));
} else { } else {
document.write('Пример работает только в IE8-'); document.write('Пример работает только в IE8-');
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,47 +1,50 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<style> <style>
#moving-div { #moving-div {
border: 5px groove green; border: 5px groove green;
padding: 5px; padding: 5px;
margin: 10px; margin: 10px;
background-color: yellow; background-color: yellow;
} }
</style> </style>
</head> </head>
<body> <body>
Before Before Before Before Before Before
<div id="moving-div"> <div id="moving-div">
Text Text Text<br> Text Text Text
Text Text Text<br> <br> Text Text Text
</div> <br>
</div>
After After After After After After
<script> <script>
var div = document.getElementById('moving-div') var div = document.getElementById('moving-div')
var placeHolder = document.createElement('div') var placeHolder = document.createElement('div')
placeHolder.style.height = div.offsetHeight + 'px' placeHolder.style.height = div.offsetHeight + 'px'
var computedStyle = div.currentStyle || getComputedStyle(div, null) var computedStyle = div.currentStyle || getComputedStyle(div, null)
placeHolder.style.marginTop = computedStyle.marginTop // full prop name placeHolder.style.marginTop = computedStyle.marginTop // full prop name
placeHolder.style.marginBottom = computedStyle.marginBottom placeHolder.style.marginBottom = computedStyle.marginBottom
// highlight it for demo purposes // highlight it for demo purposes
placeHolder.style.backgroundColor = '#C0C0C0' placeHolder.style.backgroundColor = '#C0C0C0'
document.body.insertBefore(placeHolder, div) document.body.insertBefore(placeHolder, div)
div.style.position = 'absolute' div.style.position = 'absolute'
div.style.right = div.style.top = 0 div.style.right = div.style.top = 0
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,33 +1,37 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<style> <style>
#moving-div { #moving-div {
border: 5px groove green; border: 5px groove green;
background-color: yellow; background-color: yellow;
padding: 5px; padding: 5px;
margin: 10px; margin: 10px;
} }
</style> </style>
</head> </head>
<body> <body>
Before Before Before Before Before Before
<div id="moving-div"> <div id="moving-div">
Text Text Text<br> Text Text Text
Text Text Text<br> <br> Text Text Text
</div> <br>
</div>
After After After After After After
<script> <script>
// .. Add your code here // .. Add your code here
var div = document.getElementById('moving-div') var div = document.getElementById('moving-div')
div.style.position = 'absolute' div.style.position = 'absolute'
div.style.right = div.style.top = 0 div.style.right = div.style.top = 0
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,39 +1,41 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<style>
#field {
width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball { <head>
position: absolute; <style>
} #field {
</style> width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball {
position: absolute;
}
</style>
</head> </head>
<body> <body>
<div id="field"> <div id="field">
<img src="https://js.cx/clipart/ball.svg" id="ball"> <img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div> </div>
<script> <script>
var ball = document.getElementById('ball') var ball = document.getElementById('ball')
var field = document.getElementById('field') var field = document.getElementById('field')
// ball.offsetWidth=0 before image loaded! // ball.offsetWidth=0 before image loaded!
// to fix: set width // to fix: set width
ball.style.left = Math.round(field.clientWidth / 2)+'px' ball.style.left = Math.round(field.clientWidth / 2) + 'px'
ball.style.top = Math.round(field.clientHeight / 2)+'px' ball.style.top = Math.round(field.clientHeight / 2) + 'px'
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,39 +1,41 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<style>
#field {
width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball { <head>
position: absolute; <style>
} #field {
</style> width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball {
position: absolute;
}
</style>
</head> </head>
<body> <body>
<div id="field"> <div id="field">
<img src="https://js.cx/clipart/ball.svg" width="40" height="40" id="ball"> <img src="https://js.cx/clipart/ball.svg" width="40" height="40" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div> </div>
<script> <script>
var ball = document.getElementById('ball') var ball = document.getElementById('ball')
var field = document.getElementById('field') var field = document.getElementById('field')
// ball.offsetWidth=0 before image loaded! // ball.offsetWidth=0 before image loaded!
// to fix: set width // to fix: set width
ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2)+'px' ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px'
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2)+'px' ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px'
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,27 +1,30 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<style>
#field {
width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball { <head>
position: absolute; <style>
} #field {
</style> width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball {
position: absolute;
}
</style>
</head> </head>
<body> <body>
<div id="field"> <div id="field">
<img src="https://js.cx/clipart/ball.svg" id="ball"> <img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div> </div>
</body> </body>
</html> </html>

View file

@ -1,56 +1,53 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
#elem { #elem {
width: 200px; width: 200px;
height: 150px; height: 150px;
background-color: red; background-color: red;
padding: 20px; padding: 20px;
overflow: auto; overflow: auto;
/* position: absolute */ /* position: absolute */
} }
body { body {
border: 1px solid black; border: 1px solid black;
} }
</style> </style>
</head> </head>
<body> <body>
<div id="elem"> <div id="elem">
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст </div>
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
</div>
<script> <script>
var elem = document.getElementById("elem"); var elem = document.getElementById("elem");
// неверно! // неверно!
//elem.style.width = '100%'; //elem.style.width = '100%';
// верно (так как обычный div по умолчанию растягивается во всю ширину) // верно (так как обычный div по умолчанию растягивается во всю ширину)
//elem.style.width = 'auto'; //elem.style.width = 'auto';
// верно (решение с JS) // верно (решение с JS)
var bodyWidth = document.body.clientWidth; var bodyWidth = document.body.clientWidth;
var style = getComputedStyle(elem); var style = getComputedStyle(elem);
var bodyInnerWidth = bodyWidth - parseInt(style.paddingLeft) - parseInt(style.paddingRight); var bodyInnerWidth = bodyWidth - parseInt(style.paddingLeft) - parseInt(style.paddingRight);
elem.style.width = bodyInnerWidth + 'px'; elem.style.width = bodyInnerWidth + 'px';
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
@ -14,28 +15,25 @@
body { body {
border: 1px solid black; border: 1px solid black;
} }
</style> </style>
</head> </head>
<body> <body>
<div id="elem"> <div id="elem">
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст </div>
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
</div>
<script> <script>
var elem = document.getElementById("elem"); var elem = document.getElementById("elem");
// ... ваш код // ... ваш код
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,24 +1,26 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<div id="elem" style="overflow-y:scroll;width:300px;height:200px;border:1px solid black"> <div id="elem" style="overflow-y:scroll;width:300px;height:200px;border:1px solid black">
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст </div>
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
</div>
<script> <script>
// FF: 200, Ch/Sa: 184, Op: 200, IE9: 184, IE7,8:200 // FF: 200, Ch/Sa: 184, Op: 200, IE9: 184, IE7,8:200
</script> </script>
У элемента стоит <code>style="width:300px"</code><br> У элемента стоит <code>style="width:300px"</code>
<br>
<button onclick="alert( getComputedStyle(elem).width )">alert( getComputedStyle(elem).width )</button> <button onclick="alert( getComputedStyle(elem).width )">alert( getComputedStyle(elem).width )</button>
</body> </body>
</html> </html>

View file

@ -1,91 +1,94 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<meta charset="utf-8">
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#example { <head>
width: 300px; <meta charset="utf-8">
height: 200px; <style type="text/css">
overflow: auto; * {
border: 25px solid #E8C48F; margin: 0;
padding: 20px; padding: 0;
} }
.key {
cursor: pointer; #example {
text-decoration: underline; width: 300px;
} height: 200px;
</style> overflow: auto;
border: 25px solid #E8C48F;
padding: 20px;
}
.key {
cursor: pointer;
text-decoration: underline;
}
</style>
</head> </head>
<body> <body>
<div id="example"> <div id="example">
<h3>Introduction</h3> <h3>Introduction</h3>
<p>This Ecma Standard is based on several originating technologies, the most well known being JavaScript (Netscape) and JScript (Microsoft). The language was invented by Brendan Eich at Netscape and first appeared in that company's Navigator 2.0 browser. It has appeared in all subsequent browsers from Netscape and in all browsers from Microsoft starting with Internet Explorer 3.0. The development of this Standard started in November 1996. The first edition of this Ecma Standard was adopted by the Ecma General Assembly of June 1997.</p> <p>This Ecma Standard is based on several originating technologies, the most well known being JavaScript (Netscape) and JScript (Microsoft). The language was invented by Brendan Eich at Netscape and first appeared in that company's Navigator 2.0 browser.
It has appeared in all subsequent browsers from Netscape and in all browsers from Microsoft starting with Internet Explorer 3.0. The development of this Standard started in November 1996. The first edition of this Ecma Standard was adopted by the
Ecma General Assembly of June 1997.</p>
<p>That Ecma Standard was submitted to ISO/IEC JTC 1 for adoption under the fast-track procedure, and approved as international standard ISO/IEC 16262, in April 1998. The Ecma General Assembly of June 1998 approved the second edition of ECMA-262 to keep it fully aligned with ISO/IEC 16262. Changes between the first and the second edition are editorial in nature.</p> <p>That Ecma Standard was submitted to ISO/IEC JTC 1 for adoption under the fast-track procedure, and approved as international standard ISO/IEC 16262, in April 1998. The Ecma General Assembly of June 1998 approved the second edition of ECMA-262 to keep
it fully aligned with ISO/IEC 16262. Changes between the first and the second edition are editorial in nature.</p>
<p>The third edition of the Standard introduced powerful regular expressions, better string handling, new control statements, try/catch exception handling, tighter definition of errors, formatting for numeric output and minor changes in anticipation of forthcoming internationalisation facilities and future language growth. The third edition of the ECMAScript standard was adopted by the Ecma General Assembly of December 1999 and published as ISO/IEC 16262:2002 in June 2002.</p> <p>The third edition of the Standard introduced powerful regular expressions, better string handling, new control statements, try/catch exception handling, tighter definition of errors, formatting for numeric output and minor changes in anticipation
of forthcoming internationalisation facilities and future language growth. The third edition of the ECMAScript standard was adopted by the Ecma General Assembly of December 1999 and published as ISO/IEC 16262:2002 in June 2002.</p>
</div> </div>
<div id="mouse-wrap">Координаты мыши: <span id="mouse">...</span></div> <div id="mouse-wrap">Координаты мыши: <span id="mouse">...</span></div>
<div id="info"></div> <div id="info"></div>
<script> <script>
var example = document.getElementById('example') var example = document.getElementById('example')
var info = document.getElementById('info') var info = document.getElementById('info')
var props = { var props = {
'размеры': 'размеры': ['clientLeft', 'clientTop', 'clientWidth', 'clientHeight', 'offsetWidth', 'offsetHeight', 'scrollWidth', 'scrollHeight'],
['clientLeft','clientTop', 'clientWidth','clientHeight','offsetWidth','offsetHeight','scrollWidth', 'scrollHeight'], 'прокрутка': ['scrollLeft', 'scrollTop'],
'прокрутка': 'позиционирование по рендерингу': ['offsetParent', 'offsetLeft', 'offsetTop']
['scrollLeft','scrollTop'] , }
'позиционирование по рендерингу':
['offsetParent', 'offsetLeft','offsetTop']
}
info.innerHTML = '<h3>Нажмите для просмотра значения:</h3>'; info.innerHTML = '<h3>Нажмите для просмотра значения:</h3>';
for (var k in props) { for (var k in props) {
info.innerHTML += '<h4>' + k + '</h4>'; info.innerHTML += '<h4>' + k + '</h4>';
var prop = props[k]; var prop = props[k];
for (var i = 0; i < prop.length; i++) { for (var i = 0; i < prop.length; i++) {
info.innerHTML += "<span class='key'>"+prop[i]+'</span>: <span id="'+prop[i]+'">&nbsp;</span>' + " " info.innerHTML += "<span class='key'>" + prop[i] + '</span>: <span id="' + prop[i] + '">&nbsp;</span>' + " "
i++; i++;
if (i<prop.length) { if (i < prop.length) {
info.innerHTML += "<span class='key'>"+prop[i]+'</span>: <span id="'+prop[i]+'">&nbsp;</span>'; info.innerHTML += "<span class='key'>" + prop[i] + '</span>: <span id="' + prop[i] + '">&nbsp;</span>';
} }
info.innerHTML += "<br/>"; info.innerHTML += "<br/>";
}
} }
}
document.onclick = function(event) { document.onclick = function(event) {
var target = event.target; var target = event.target;
if (!target.classList.contains('key')) return; if (!target.classList.contains('key')) return;
var prop = target.innerHTML; var prop = target.innerHTML;
var value = example[prop]; var value = example[prop];
value = value.tagName || value; value = value.tagName || value;
document.getElementById(prop).innerHTML = value; document.getElementById(prop).innerHTML = value;
}; };
document.onmousemove = function(e) { document.onmousemove = function(e) {
document.getElementById('mouse').innerHTML = Math.round(e.clientX)+':'+Math.round(e.clientY); document.getElementById('mouse').innerHTML = Math.round(e.clientX) + ':' + Math.round(e.clientY);
}; };
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,23 +1,27 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
<script> <script>
document.onclick = function(e) { // выводит текущие координаты при клике document.onclick = function(e) { // выводит текущие координаты при клике
document.getElementById('coords').innerHTML = e.clientX + ':' + e.clientY; document.getElementById('coords').innerHTML = e.clientX + ':' + e.clientY;
}; };
</script> </script>
</head> </head>
<body> <body>
Кликните на любое место, чтобы получить координаты относительно окна.<br> Кликните на любое место, чтобы получить координаты относительно окна.
Это для удобства тестирования, чтобы проверить результат, который вы получите из DOM.<br> <br> Это для удобства тестирования, чтобы проверить результат, который вы получите из DOM.
<br>
<div id="coords">(координаты появятся тут)</div> <div id="coords">(координаты появятся тут)</div>
<div id="field"> <div id="field">
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div> </div>
@ -28,35 +32,34 @@
<script> <script>
var field = document.getElementById('field');
var field = document.getElementById('field'); // полное решение - в массиве result
// полное решение - в массиве result var fieldCoords = field.getBoundingClientRect();
var fieldCoords = field.getBoundingClientRect(); var result = [
[ // 1
var result = [ fieldCoords.left,
[ // 1 fieldCoords.top
fieldCoords.left, ],
fieldCoords.top [ // 2
], fieldCoords.right,
[ // 2 fieldCoords.bottom
fieldCoords.right, ],
fieldCoords.bottom [ // 3
], fieldCoords.left + field.clientLeft,
[ // 3 fieldCoords.top + field.clientTop
fieldCoords.left + field.clientLeft, ],
fieldCoords.top + field.clientTop [ // 4
], fieldCoords.left + field.clientLeft + field.clientWidth,
[ // 4 fieldCoords.top + field.clientTop + field.clientHeight
fieldCoords.left + field.clientLeft + field.clientWidth, ]
fieldCoords.top + field.clientTop + field.clientHeight ];
]
];
alert(result.join(' '));
alert(result.join(' '));
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,23 +1,27 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
<script> <script>
document.onclick = function(e) { // выводит текущие координаты при клике document.onclick = function(e) { // выводит текущие координаты при клике
document.getElementById('coords').innerHTML = e.clientX + ':' + e.clientY; document.getElementById('coords').innerHTML = e.clientX + ':' + e.clientY;
}; };
</script> </script>
</head> </head>
<body> <body>
Кликните на любое место, чтобы получить координаты относительно окна.<br> Кликните на любое место, чтобы получить координаты относительно окна.
Это для удобства тестирования, чтобы проверить результат, который вы получите из DOM.<br> <br> Это для удобства тестирования, чтобы проверить результат, который вы получите из DOM.
<br>
<div id="coords">(координаты появятся тут)</div> <div id="coords">(координаты появятся тут)</div>
<div id="field"> <div id="field">
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div> </div>
@ -28,12 +32,11 @@
<script> <script>
var field = document.getElementById('field');
var field = document.getElementById('field'); // ваш код...
// ваш код...
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,30 +1,26 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
</head> </head>
<body> <body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae esse sequi officia sapiente.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
esse sequi officia sapiente.</p>
<blockquote> <blockquote>
- Что на завтрак, Бэрримор? - Что на завтрак, Бэрримор? - Овсянка, сэр. - А на обед? - Овсянка, сэр. - Ну а на ужин? - Котлеты, сэр. - Уррра!!! - Из овсянки, сэр!!!
- Овсянка, сэр.
- А на обед?
- Овсянка, сэр.
- Ну а на ужин?
- Котлеты, сэр.
- Уррра!!!
- Из овсянки, сэр!!!
</blockquote> </blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae esse sequi officia sapiente.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
esse sequi officia sapiente.</p>
<script> <script>
/** /**
* Позиционирует элемент elem относительно элемента anchor, как указано в * Позиционирует элемент elem относительно элемента anchor, как указано в
* в position. * в position.
@ -39,21 +35,21 @@
var anchorCoords = anchor.getBoundingClientRect(); var anchorCoords = anchor.getBoundingClientRect();
switch(position) { switch (position) {
case "top": case "top":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px"; elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break; break;
case "right": case "right":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px"; elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px"; elem.style.top = anchorCoords.top + "px";
break; break;
case "bottom": case "bottom":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px"; elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break; break;
} }
} }
@ -82,4 +78,5 @@
</body> </body>
</html> </html>

View file

@ -1,30 +1,26 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
</head> </head>
<body> <body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae esse sequi officia sapiente.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
esse sequi officia sapiente.</p>
<blockquote> <blockquote>
- Что на завтрак, Бэрримор? - Что на завтрак, Бэрримор? - Овсянка, сэр. - А на обед? - Овсянка, сэр. - Ну а на ужин? - Котлеты, сэр. - Уррра!!! - Из овсянки, сэр!!!
- Овсянка, сэр.
- А на обед?
- Овсянка, сэр.
- Ну а на ужин?
- Котлеты, сэр.
- Уррра!!!
- Из овсянки, сэр!!!
</blockquote> </blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae esse sequi officia sapiente.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
esse sequi officia sapiente.</p>
<script> <script>
/** /**
* Позиционирует элемент elem относительно элемента anchor, как указано в * Позиционирует элемент elem относительно элемента anchor, как указано в
* в position. * в position.
@ -55,4 +51,5 @@
</body> </body>
</html> </html>

View file

@ -1,9 +1,11 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
</head> </head>
<body style="height:2000px"> <body style="height:2000px">
<p>Исправления два:</p> <p>Исправления два:</p>
@ -14,21 +16,14 @@
</ol> </ol>
<blockquote> <blockquote>
- Что на завтрак, Бэрримор? - Что на завтрак, Бэрримор? - Овсянка, сэр. - А на обед? - Овсянка, сэр. - Ну а на ужин? - Котлеты, сэр. - Уррра!!! - Из овсянки, сэр!!!
- Овсянка, сэр.
- А на обед?
- Овсянка, сэр.
- Ну а на ужин?
- Котлеты, сэр.
- Уррра!!!
- Из овсянки, сэр!!!
</blockquote> </blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae esse sequi officia sapiente.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
esse sequi officia sapiente.</p>
<script> <script>
/** /**
* Вспомогательная функция для координат относительно документа * Вспомогательная функция для координат относительно документа
*/ */
@ -45,10 +40,13 @@
var clientTop = docEl.clientTop || body.clientTop || 0; var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0; var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop; var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft; var left = box.left + scrollLeft - clientLeft;
return { top: top, left: left }; return {
top: top,
left: left
};
} }
@ -56,21 +54,21 @@
var anchorCoords = getCoords(anchor); var anchorCoords = getCoords(anchor);
switch(position) { switch (position) {
case "top": case "top":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px"; elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break; break;
case "right": case "right":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px"; elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px"; elem.style.top = anchorCoords.top + "px";
break; break;
case "bottom": case "bottom":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px"; elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break; break;
} }
} }
@ -98,4 +96,5 @@
</body> </body>
</html> </html>

View file

@ -1,26 +1,23 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="index.css"> <link rel="stylesheet" href="index.css">
</head> </head>
<body style="height:2000px"> <body style="height:2000px">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae esse sequi officia sapiente.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
esse sequi officia sapiente.</p>
<blockquote> <blockquote>
- Что на завтрак, Бэрримор? - Что на завтрак, Бэрримор? - Овсянка, сэр. - А на обед? - Овсянка, сэр. - Ну а на ужин? - Котлеты, сэр. - Уррра!!! - Из овсянки, сэр!!!
- Овсянка, сэр.
- А на обед?
- Овсянка, сэр.
- Ну а на ужин?
- Котлеты, сэр.
- Уррра!!!
- Из овсянки, сэр!!!
</blockquote> </blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae esse sequi officia sapiente.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
esse sequi officia sapiente.</p>
<script> <script>
@ -36,10 +33,13 @@
var clientTop = docEl.clientTop || body.clientTop || 0; var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0; var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop; var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft; var left = box.left + scrollLeft - clientLeft;
return { top: top, left: left }; return {
top: top,
left: left
};
} }
function showNote(anchor, position, html) { function showNote(anchor, position, html) {
@ -66,36 +66,36 @@
var anchorCoords = getCoords(anchor); var anchorCoords = getCoords(anchor);
switch(position) { switch (position) {
case "top-out": case "top-out":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px"; elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break; break;
case "right-out": case "right-out":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px"; elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px"; elem.style.top = anchorCoords.top + "px";
break; break;
case "bottom-out": case "bottom-out":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px"; elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break; break;
case "top-in": case "top-in":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + "px"; elem.style.top = anchorCoords.top + "px";
break; break;
case "right-in": case "right-in":
elem.style.left = anchorCoords.left + anchor.offsetWidth - elem.offsetWidth + "px"; elem.style.left = anchorCoords.left + anchor.offsetWidth - elem.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px"; elem.style.top = anchorCoords.top + "px";
break; break;
case "bottom-in": case "bottom-in":
elem.style.left = anchorCoords.left + "px"; elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight - elem.offsetHeight + "px"; elem.style.top = anchorCoords.top + anchor.offsetHeight - elem.offsetHeight + "px";
break; break;
} }
} }
@ -107,9 +107,9 @@
showNote(blockquote, "top-out", "заметка top-out"); showNote(blockquote, "top-out", "заметка top-out");
showNote(blockquote, "right-out", "заметка right-out"); showNote(blockquote, "right-out", "заметка right-out");
showNote(blockquote, "bottom-in", "заметка bottom-in"); showNote(blockquote, "bottom-in", "заметка bottom-in");
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,11 +1,13 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<body>
Правда о лосях <body>
<ol> Правда о лосях
<li>Лось — животное хитрое</li> <ol>
<!-- комментарий --> <li>Лось — животное хитрое</li>
<li>..И коварное!</li> <!-- комментарий -->
</ol> <li>..И коварное!</li>
</body> </ol>
</body>
</html> </html>

View file

@ -1,28 +1,66 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
table { border-collapse: collapse; } table {
td { border: 1px solid black; padding: 3px 5px; } border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 3px 5px;
}
</style> </style>
</head> </head>
<body> <body>
<table> <table>
<tr><td>1:1</td><td>2:1</td><td>3:1</td><td>4:1</td><td>5:1</td></tr> <tr>
<tr><td>1:2</td><td>2:2</td><td>3:2</td><td>4:2</td><td>5:2</td></tr> <td>1:1</td>
<tr><td>1:3</td><td>2:3</td><td>3:3</td><td>4:3</td><td>5:3</td></tr> <td>2:1</td>
<tr><td>1:4</td><td>2:4</td><td>3:4</td><td>4:4</td><td>5:4</td></tr> <td>3:1</td>
<tr><td>1:5</td><td>2:5</td><td>3:5</td><td>4:5</td><td>5:5</td></tr> <td>4:1</td>
<td>5:1</td>
</tr>
<tr>
<td>1:2</td>
<td>2:2</td>
<td>3:2</td>
<td>4:2</td>
<td>5:2</td>
</tr>
<tr>
<td>1:3</td>
<td>2:3</td>
<td>3:3</td>
<td>4:3</td>
<td>5:3</td>
</tr>
<tr>
<td>1:4</td>
<td>2:4</td>
<td>3:4</td>
<td>4:4</td>
<td>5:4</td>
</tr>
<tr>
<td>1:5</td>
<td>2:5</td>
<td>3:5</td>
<td>4:5</td>
<td>5:5</td>
</tr>
</table> </table>
<script> <script>
var table = document.body.children[0]; var table = document.body.children[0];
for(var i=0; i<table.rows.length; i++) { for (var i = 0; i < table.rows.length; i++) {
var row = table.rows[i]; var row = table.rows[i];
row.cells[i].style.backgroundColor = 'red'; row.cells[i].style.backgroundColor = 'red';
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,25 +1,63 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
table { border-collapse: collapse; } table {
td { border: 1px solid black; padding: 3px 5px; } border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 3px 5px;
}
</style> </style>
</head> </head>
<body> <body>
<table> <table>
<tr><td>1:1</td><td>2:1</td><td>3:1</td><td>4:1</td><td>5:1</td></tr> <tr>
<tr><td>1:2</td><td>2:2</td><td>3:2</td><td>4:2</td><td>5:2</td></tr> <td>1:1</td>
<tr><td>1:3</td><td>2:3</td><td>3:3</td><td>4:3</td><td>5:3</td></tr> <td>2:1</td>
<tr><td>1:4</td><td>2:4</td><td>3:4</td><td>4:4</td><td>5:4</td></tr> <td>3:1</td>
<tr><td>1:5</td><td>2:5</td><td>3:5</td><td>4:5</td><td>5:5</td></tr> <td>4:1</td>
<td>5:1</td>
</tr>
<tr>
<td>1:2</td>
<td>2:2</td>
<td>3:2</td>
<td>4:2</td>
<td>5:2</td>
</tr>
<tr>
<td>1:3</td>
<td>2:3</td>
<td>3:3</td>
<td>4:3</td>
<td>5:3</td>
</tr>
<tr>
<td>1:4</td>
<td>2:4</td>
<td>3:4</td>
<td>4:4</td>
<td>5:4</td>
</tr>
<tr>
<td>1:5</td>
<td>2:5</td>
<td>3:5</td>
<td>4:5</td>
<td>5:5</td>
</tr>
</table> </table>
<script> <script>
var table = document.body.children[0]; var table = document.body.children[0];
/* ваш код */ /* ваш код */
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,42 +1,48 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<meta charset="utf-8">
</head>
<body> <head>
<form name="search"> <meta charset="utf-8">
<label>Поиск по сайту: <input type="text" name="search"></label> </head>
<input type="submit" value="Искать!">
</form>
<hr> <body>
<form name="search">
<label>Поиск по сайту:
<input type="text" name="search">
</label>
<input type="submit" value="Искать!">
</form>
<form name="search-person"> <hr>
Поиск по посетителям:
<table id="age-table">
<tr>
<td>Возраст:</td>
<td id="age-list">
<label><input type="radio" name="age" value="young">до 18</label>
<label><input type="radio" name="age" value="mature">18-50</label>
<label><input type="radio" name="age" value="senior">более 50</label>
</td>
</tr>
<tr> <form name="search-person">
<td>Дополнительно:</td> Поиск по посетителям:
<td> <table id="age-table">
<input type="text" name="info[0]"> <tr>
<input type="text" name="info[1]"> <td>Возраст:</td>
<input type="text" name="info[2]"> <td id="age-list">
</td> <label>
</tr> <input type="radio" name="age" value="young">до 18</label>
<label>
<input type="radio" name="age" value="mature">18-50</label>
<label>
<input type="radio" name="age" value="senior">более 50</label>
</td>
</tr>
</table> <tr>
<td>Дополнительно:</td>
<td>
<input type="text" name="info[0]">
<input type="text" name="info[1]">
<input type="text" name="info[2]">
</td>
</tr>
<input type="submit" value="Искать!"> </table>
</form>
</body> <input type="submit" value="Искать!">
</form>
</body>
</html> </html>

View file

@ -1,61 +1,66 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<ul> <ul>
<li>Животные <li>Животные
<ul> <ul>
<li>Млекопитающие <li>Млекопитающие
<ul> <ul>
<li>Коровы</li> <li>Коровы</li>
<li>Ослы</li> <li>Ослы</li>
<li>Собаки</li> <li>Собаки</li>
<li>Тигры</li> <li>Тигры</li>
</ul> </ul>
</li> </li>
<li>Другие <li>Другие
<ul> <ul>
<li>Змеи</li> <li>Змеи</li>
<li>Птицы</li> <li>Птицы</li>
<li>Ящерицы</li> <li>Ящерицы</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
<li>Рыбы <li>Рыбы
<ul> <ul>
<li>Аквариумные <li>Аквариумные
<ul> <ul>
<li>Гуппи</li> <li>Гуппи</li>
<li>Скалярии</li> <li>Скалярии</li>
</ul> </ul>
</li> </li>
<li>Морские <li>Морские
<ul> <ul>
<li>Морская форель</li> <li>Морская форель</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
</ul> </ul>
<script> <script>
var lis = document.getElementsByTagName('li'); var lis = document.getElementsByTagName('li');
for(i=0; i<lis.length; i++) { for (i = 0; i < lis.length; i++) {
// получить название из текстового узла // получить название из текстового узла
var title = lis[i].firstChild.data; var title = lis[i].firstChild.data;
title = title.trim(); // убрать лишние пробелы с концов title = title.trim(); // убрать лишние пробелы с концов
// получить количество детей // получить количество детей
var childCount = lis[i].getElementsByTagName('li').length; var childCount = lis[i].getElementsByTagName('li').length;
alert(title + ': ' + childCount); alert(title + ': ' + childCount);
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,49 +1,54 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<ul> <ul>
<li>Животные <li>Животные
<ul> <ul>
<li>Млекопитающие <li>Млекопитающие
<ul> <ul>
<li>Коровы</li> <li>Коровы</li>
<li>Ослы</li> <li>Ослы</li>
<li>Собаки</li> <li>Собаки</li>
<li>Тигры</li> <li>Тигры</li>
</ul> </ul>
</li> </li>
<li>Другие <li>Другие
<ul> <ul>
<li>Змеи</li> <li>Змеи</li>
<li>Птицы</li> <li>Птицы</li>
<li>Ящерицы</li> <li>Ящерицы</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
<li>Рыбы <li>Рыбы
<ul> <ul>
<li>Аквариумные <li>Аквариумные
<ul> <ul>
<li>Гуппи</li> <li>Гуппи</li>
<li>Скалярии</li> <li>Скалярии</li>
</ul> </ul>
</li> </li>
<li>Морские <li>Морские
<ul> <ul>
<li>Морская форель</li> <li>Морская форель</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
</ul> </ul>
<script> <script>
// .. ваш код .. // .. ваш код ..
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,70 +1,207 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
p { p {
display: inline-block; display: inline-block;
margin: 0; margin: 0;
} }
</style> </style>
</head> </head>
<body> <body>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>1</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>2</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>3</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>4</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>5</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>6</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>7</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>8</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>9</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>1</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>2</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>3</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>4</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>5</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>6</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>7</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<script> <script>
function bench(f, times) { function bench(f, times) {
var d = new Date(); var d = new Date();
for(var i=0; i<times; i++) f(); for (var i = 0; i < times; i++) f();
return new Date() - d; return new Date() - d;
} }
function runGetList() { function runGetList() {
var results = document.getElementsByTagName('p'); var results = document.getElementsByTagName('p');
var len = results.length; var len = results.length;
for(var i = 0; i<len; i++) { for (var i = 0; i < len; i++) {
var elem = results[i]; var elem = results[i];
} }
} }
function runQueryList() { function runQueryList() {
var results = document.querySelectorAll('p'); var results = document.querySelectorAll('p');
var len = results.length; var len = results.length;
for(var i = 0; i<len; i++) { for (var i = 0; i < len; i++) {
var elem = results[i]; var elem = results[i];
} }
} }
function log(msg) { function log(msg) {
alert(msg); alert(msg);
} }
log( 'getElementsByTagName: ' + bench(runGetList, 10000) ); log('getElementsByTagName: ' + bench(runGetList, 10000));
log( 'querySelectorAll: ' + bench(runQueryList, 10000) ); log('querySelectorAll: ' + bench(runQueryList, 10000));
</script>
</script>
</body> </body>
</html>
</html>

View file

@ -1,32 +1,170 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>1</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>2</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>3</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>4</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>5</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>6</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>7</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>8</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>9</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>1</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>2</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>3</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>4</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>5</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>6</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>7</p>
<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p> <p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<script> <script>
// ... // ...
</script> </script>
</body> </body>
</html>
</html>

View file

@ -1,5 +1,6 @@
<!DOCTYLE HTML> <!DOCTYLE HTML>
<html> <html>
<body> <body>
<div data-widget-name="menu">Выберите жанр</div> <div data-widget-name="menu">Выберите жанр</div>
@ -9,4 +10,5 @@
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,36 +1,38 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
.external { .external {
background-color: yellow; background-color: yellow;
} }
</style> </style>
</head> </head>
<body> <body>
<a name="list">список</a> <a name="list">список</a>
<ul> <ul>
<li><a href="http://google.com">http://google.com</a></li> <li><a href="http://google.com">http://google.com</a></li>
<li><a href="/tutorial">/tutorial.html</a></li> <li><a href="/tutorial">/tutorial.html</a></li>
<li><a href="local/path">local/path</a></li> <li><a href="local/path">local/path</a></li>
<li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li> <li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li>
<li><a href="http://nodejs.org">http://nodejs.org</a></li> <li><a href="http://nodejs.org">http://nodejs.org</a></li>
<li><a href="http://internal.com/test">http://internal.com/test</a></li> <li><a href="http://internal.com/test">http://internal.com/test</a></li>
</ul> </ul>
<script> <script>
var css = 'a[href*="://"]:not([href^="http://internal.com"])';
var links = document.querySelectorAll(css);
var css = 'a[href*="://"]:not([href^="http://internal.com"])'; for (var i = 0; i < links.length; i++) {
var links = document.querySelectorAll(css); links[i].classList.add('external');
}
for(var i=0; i<links.length; i++) { </script>
links[i].classList.add('external');
}
</script>
</body> </body>
</html> </html>

View file

@ -1,20 +1,23 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<input type="button" id="hider" value="Нажмите, чтобы спрятать текст"/> <input type="button" id="hider" value="Нажмите, чтобы спрятать текст" />
<div id="text">Текст</div> <div id="text">Текст</div>
<script> <script>
// в этой задаче неважно, как именно прятать элемент // в этой задаче неважно, как именно прятать элемент
// например через style.display: // например через style.display:
document.getElementById('hider').onclick = function() { document.getElementById('hider').onclick = function() {
document.getElementById('text').style.display = 'none'; document.getElementById('text').style.display = 'none';
} }
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,16 +1,19 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<input type="button" id="hider" value="Нажмите, чтобы спрятать текст"/> <input type="button" id="hider" value="Нажмите, чтобы спрятать текст" />
<div id="text">Текст</div> <div id="text">Текст</div>
<script> <script>
/* ваш код */ /* ваш код */
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,58 +1,58 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
.menu ul {
margin: 0;
list-style: none;
padding-left: 20px;
display: none;
}
.menu ul { .menu .title {
margin: 0; font-size: 18px;
list-style: none; cursor: pointer;
padding-left: 20px; }
display: none; .menu .title::before {
} content: '▶ ';
font-size: 80%;
color: green;
}
.menu .title { .menu.open .title::before {
font-size: 18px; content: '▼ ';
cursor: pointer; }
}
.menu .title::before { .menu.open ul {
content: '▶ '; display: block;
font-size: 80%; }
color: green; </style>
}
.menu.open .title::before {
content: '▼ ';
}
.menu.open ul {
display: block;
}
</style>
</head> </head>
<body> <body>
<div id="sweeties" class="menu"> <div id="sweeties" class="menu">
<span class="title">Сладости (нажми меня)!</span> <span class="title">Сладости (нажми меня)!</span>
<ul> <ul>
<li>Торт</li> <li>Торт</li>
<li>Пончик</li> <li>Пончик</li>
<li>Пирожное</li> <li>Пирожное</li>
</ul> </ul>
</div> </div>
<script> <script>
var menuElem = document.getElementById('sweeties'); var menuElem = document.getElementById('sweeties');
var titleElem = menuElem.querySelector('.title'); var titleElem = menuElem.querySelector('.title');
titleElem.onclick = function() { titleElem.onclick = function() {
menuElem.classList.toggle('open'); menuElem.classList.toggle('open');
}; };
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,17 +1,20 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
▶ ▼ Сладости (нажми меня)! ▶ ▼ Сладости (нажми меня)!
<ul> <ul>
<li>Торт</li> <li>Торт</li>
<li>Пончик</li> <li>Пончик</li>
<li>Пирожное</li> <li>Пирожное</li>
</ul> </ul>
</body> </body>
</html> </html>

View file

@ -1,46 +1,46 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<link rel="stylesheet" href="messages.css"> <link rel="stylesheet" href="messages.css">
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="messages-container"> <div id="messages-container">
<div class="pane"> <div class="pane">
<h3>Лошадь</h3> <h3>Лошадь</h3>
<p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p> <p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p>
<button class="remove-button">[x]</button> <button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Осёл</h3>
<p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3>
<p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют
тёлками.</p>
<button class="remove-button">[x]</button>
</div>
</div> </div>
<div class="pane">
<h3>Осёл</h3>
<p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3>
<p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют тёлками.</p>
<button class="remove-button">[x]</button>
</div>
</div>
<script> <script>
var buttons = document.querySelectorAll('#messages-container .remove-button');
var buttons = document.querySelectorAll('#messages-container .remove-button'); for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
for(var i=0; i<buttons.length; i++) { button.onclick = function() {
var button = buttons[i]; var el = this.parentNode;
el.parentNode.removeChild(el);
button.onclick = function() { };
var el = this.parentNode; }
el.parentNode.removeChild(el); </script>
};
}
</script>
</body> </body>
</html> </html>

View file

@ -1,28 +1,32 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<link rel="stylesheet" type="text/css" href="messages.css"> <link rel="stylesheet" type="text/css" href="messages.css">
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
Кнопка для удаления: <button class="remove-button">[x]</button> Кнопка для удаления:
<button class="remove-button">[x]</button>
<div> <div>
<div class="pane"> <div class="pane">
<h3>Лошадь</h3> <h3>Лошадь</h3>
<p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p> <p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p>
</div> </div>
<div class="pane"> <div class="pane">
<h3>Осёл</h3> <h3>Осёл</h3>
<p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p> <p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p>
</div> </div>
<div class="pane"> <div class="pane">
<h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3> <h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3>
<p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют тёлками.</p> <p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют
</div> тёлками.</p>
</div> </div>
</div>
</body> </body>
</html> </html>

View file

@ -1,4 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
@ -6,67 +7,66 @@
<body> <body>
<div id="carousel" class="carousel"> <div id="carousel" class="carousel">
<button class="arrow prev"></button> <button class="arrow prev"></button>
<div class="gallery"> <div class="gallery">
<ul class="images"> <ul class="images">
<li><img src="https://js.cx/carousel/1.png"> <li><img src="https://js.cx/carousel/1.png">
<li><img src="https://js.cx/carousel/2.png"> <li><img src="https://js.cx/carousel/2.png">
<li><img src="https://js.cx/carousel/3.png"> <li><img src="https://js.cx/carousel/3.png">
<li><img src="https://js.cx/carousel/4.png"> <li><img src="https://js.cx/carousel/4.png">
<li><img src="https://js.cx/carousel/5.png"> <li><img src="https://js.cx/carousel/5.png">
<li><img src="https://js.cx/carousel/6.png"> <li><img src="https://js.cx/carousel/6.png">
<li><img src="https://js.cx/carousel/7.png"> <li><img src="https://js.cx/carousel/7.png">
<li><img src="https://js.cx/carousel/8.png"> <li><img src="https://js.cx/carousel/8.png">
<li><img src="https://js.cx/carousel/9.png"> <li><img src="https://js.cx/carousel/9.png">
<li><img src="https://js.cx/carousel/10.png"> <li><img src="https://js.cx/carousel/10.png">
</ul> </ul>
</div>
<button class="arrow next"></button>
</div> </div>
<button class="arrow next"></button>
</div>
<script> <script>
/* этот код помечает картинки, для удобства разработки */
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
lis[i].style.position = 'relative';
var span = document.createElement('span');
// обычно лучше использовать CSS-классы,
// но этот код - для удобства разработки, так что не будем трогать стили
span.style.cssText = 'position:absolute;left:0;top:0';
span.innerHTML = i + 1;
lis[i].appendChild(span);
}
/* этот код помечает картинки, для удобства разработки */ /* конфигурация */
var lis = document.getElementsByTagName('li'); var width = 130; // ширина изображения
for(var i=0; i<lis.length; i++) { var count = 3; // количество изображений
lis[i].style.position='relative';
var span = document.createElement('span');
// обычно лучше использовать CSS-классы,
// но этот код - для удобства разработки, так что не будем трогать стили
span.style.cssText='position:absolute;left:0;top:0';
span.innerHTML = i+1;
lis[i].appendChild(span);
}
/* конфигурация */ var carousel = document.getElementById('carousel');
var width = 130; // ширина изображения var list = carousel.querySelector('ul');
var count = 3; // количество изображений var listElems = carousel.querySelectorAll('li');
var carousel = document.getElementById('carousel'); var position = 0; // текущий сдвиг влево
var list = carousel.querySelector('ul');
var listElems = carousel.querySelectorAll('li');
var position = 0; // текущий сдвиг влево carousel.querySelector('.prev').onclick = function() {
if (position >= 0) return; // уже сдвинулись до упора
carousel.querySelector('.prev').onclick = function() { // сдвиг влево
if (position >= 0) return; // уже сдвинулись до упора // последнее передвижение влево может быть не на 3, а на 2 или 1 элемент
position = Math.min(position + width * count, 0)
list.style.marginLeft = position + 'px';
};
// сдвиг влево carousel.querySelector('.next').onclick = function() {
// последнее передвижение влево может быть не на 3, а на 2 или 1 элемент if (position <= -width * (listElems.length - count)) return; // уже до упора
position = Math.min(position + width*count, 0)
list.style.marginLeft = position + 'px';
};
carousel.querySelector('.next').onclick = function() { // сдвиг вправо
if (position <= -width*(listElems.length-count)) return; // уже до упора // последнее передвижение вправо может быть не на 3, а на 2 или 1 элемент
position = Math.max(position - width * count, -width * (listElems.length - count));
// сдвиг вправо list.style.marginLeft = position + 'px';
// последнее передвижение вправо может быть не на 3, а на 2 или 1 элемент };
position = Math.max(position-width*count, -width*(listElems.length-count)); </script>
list.style.marginLeft = position + 'px';
};
</script>
</body> </body>
</html> </html>

View file

@ -1,4 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
@ -6,43 +7,42 @@
<body> <body>
<!-- ваша верстка виджета, ваши стили --> <!-- ваша верстка виджета, ваши стили -->
<button class="arrow"></button> <button class="arrow"></button>
<button class="arrow"></button> <button class="arrow"></button>
<ul> <ul>
<li><img src="https://js.cx/carousel/1.png"> <li><img src="https://js.cx/carousel/1.png">
<li><img src="https://js.cx/carousel/2.png"> <li><img src="https://js.cx/carousel/2.png">
<li><img src="https://js.cx/carousel/3.png"> <li><img src="https://js.cx/carousel/3.png">
<li><img src="https://js.cx/carousel/4.png"> <li><img src="https://js.cx/carousel/4.png">
<li><img src="https://js.cx/carousel/5.png"> <li><img src="https://js.cx/carousel/5.png">
<li><img src="https://js.cx/carousel/6.png"> <li><img src="https://js.cx/carousel/6.png">
<li><img src="https://js.cx/carousel/7.png"> <li><img src="https://js.cx/carousel/7.png">
<li><img src="https://js.cx/carousel/8.png"> <li><img src="https://js.cx/carousel/8.png">
<li><img src="https://js.cx/carousel/9.png"> <li><img src="https://js.cx/carousel/9.png">
<li><img src="https://js.cx/carousel/10.png"> <li><img src="https://js.cx/carousel/10.png">
</ul> </ul>
<script> <script>
/* этот код помечает картинки цифрами, для удобства разработки /* этот код помечает картинки цифрами, для удобства разработки
его можно убрать, если не нужен */ его можно убрать, если не нужен */
var lis = document.getElementsByTagName('li'); var lis = document.getElementsByTagName('li');
for(var i=0; i<lis.length; i++) { for (var i = 0; i < lis.length; i++) {
lis[i].style.position='relative'; lis[i].style.position = 'relative';
var span = document.createElement('span'); var span = document.createElement('span');
span.style.cssText='position:absolute;left:0;top:0'; span.style.cssText = 'position:absolute;left:0;top:0';
span.innerHTML = i+1; span.innerHTML = i + 1;
lis[i].appendChild(span); lis[i].appendChild(span);
} }
</script> </script>
<script> <script>
// ваш код..
// ваш код.. </script>
</script>
</body> </body>
</html> </html>

View file

@ -1,93 +1,92 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
#field { #field {
width: 200px; width: 200px;
height: 150px; height: 150px;
border: 10px groove black; border: 10px groove black;
background-color: #00FF00; background-color: #00FF00;
position: relative; position: relative;
overflow: hidden; overflow: hidden;
cursor: pointer; cursor: pointer;
} }
#ball {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
-ms-transition: all 1s;
transition: all 1s;
}
#ball {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
-ms-transition: all 1s;
transition: all 1s;
}
</style> </style>
</head> </head>
<body style="height:2000px"> <body style="height:2000px">
Кликните на любое место поля, чтобы мяч перелетел туда.<br> Кликните на любое место поля, чтобы мяч перелетел туда.
<br>
<div id="field"> <div id="field">
<img src="https://js.cx/clipart/ball.svg" id="ball"> <img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div> </div>
<script> <script>
var field = document.getElementById('field');
var field = document.getElementById('field'); var ball = document.getElementById('ball');
var ball = document.getElementById('ball');
field.onclick = function(event) { field.onclick = function(event) {
// координаты поля относительно окна // координаты поля относительно окна
var fieldCoords = this.getBoundingClientRect(); var fieldCoords = this.getBoundingClientRect();
// координаты левого-верхнего внутреннего угла поля // координаты левого-верхнего внутреннего угла поля
var fieldInnerCoords = { var fieldInnerCoords = {
top: fieldCoords.top + field.clientTop, top: fieldCoords.top + field.clientTop,
left: fieldCoords.left + field.clientLeft left: fieldCoords.left + field.clientLeft
}; };
// разместить по клику, // разместить по клику,
// но сдвинув относительно поля (т.к. position:relative) // но сдвинув относительно поля (т.к. position:relative)
// и сдвинув на половину ширины/высоты // и сдвинув на половину ширины/высоты
// (!) используются координаты относительно окна clientX/Y, как и в fieldCoords // (!) используются координаты относительно окна clientX/Y, как и в fieldCoords
var ballCoords = { var ballCoords = {
top: event.clientY - fieldInnerCoords.top - ball.clientHeight / 2, top: event.clientY - fieldInnerCoords.top - ball.clientHeight / 2,
left: event.clientX - fieldInnerCoords.left - ball.clientWidth / 2 left: event.clientX - fieldInnerCoords.left - ball.clientWidth / 2
}; };
// вылезает за верхнюю границу - разместить по ней // вылезает за верхнюю границу - разместить по ней
if(ballCoords.top < 0) ballCoords.top = 0; if (ballCoords.top < 0) ballCoords.top = 0;
// вылезает за левую границу - разместить по ней // вылезает за левую границу - разместить по ней
if(ballCoords.left < 0) ballCoords.left = 0; if (ballCoords.left < 0) ballCoords.left = 0;
// вылезает за правую границу - разместить по ней // вылезает за правую границу - разместить по ней
if(ballCoords.left + ball.clientWidth > field.clientWidth) { if (ballCoords.left + ball.clientWidth > field.clientWidth) {
ballCoords.left = field.clientWidth - ball.clientWidth; ballCoords.left = field.clientWidth - ball.clientWidth;
}
// вылезает за нижнюю границу - разместить по ней
if (ballCoords.top + ball.clientHeight > field.clientHeight) {
ballCoords.top = field.clientHeight - ball.clientHeight;
}
ball.style.left = ballCoords.left + 'px';
ball.style.top = ballCoords.top + 'px';
} }
// вылезает за нижнюю границу - разместить по ней
if(ballCoords.top + ball.clientHeight > field.clientHeight) {
ballCoords.top = field.clientHeight - ball.clientHeight;
}
ball.style.left = ballCoords.left + 'px';
ball.style.top = ballCoords.top + 'px';
}
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,37 +1,40 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<meta charset="utf-8">
<style>
#field {
width: 200px;
height: 150px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
overflow: hidden;
}
#ball { <head>
position: absolute; <meta charset="utf-8">
top: 50%; <style>
left: 50%; #field {
margin-left: -20px; width: 200px;
margin-top: -20px; height: 150px;
} border: 10px groove black;
</style> background-color: #00FF00;
position: relative;
overflow: hidden;
}
#ball {
position: absolute;
top: 50%;
left: 50%;
margin-left: -20px;
margin-top: -20px;
}
</style>
</head> </head>
<body style="height:2000px"> <body style="height:2000px">
Кликните на любое место поля, чтобы мяч перелетел туда.<br> Кликните на любое место поля, чтобы мяч перелетел туда.
Мяч никогда не вылетит за границы поля. <br> Мяч никогда не вылетит за границы поля.
<div id="field"> <div id="field">
<img src="https://js.cx/clipart/ball.svg" id="ball"> <img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div> </div>
</body> </body>
</html> </html>

View file

@ -1,17 +1,20 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="example.css"> <link rel="stylesheet" href="example.css">
</head> </head>
<body> <body>
<form>FORM <form>FORM
<div>DIV <div>DIV
<p>P</p> <p>P</p>
</div> </div>
</form> </form>
<script src="script.js"></script> <script src="script.js"></script>
</body> </body>
</html> </html>

View file

@ -1,18 +1,21 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<link rel="stylesheet" href="example.css"> <link rel="stylesheet" href="example.css">
</head> </head>
<body> <body>
Клик выведет <code>event.target</code> и <code>this</code>: Клик выведет <code>event.target</code> и <code>this</code>:
<form id="form">FORM <form id="form">FORM
<div>DIV <div>DIV
<p>P</p> <p>P</p>
</div> </div>
</form> </form>
<script src="script.js"></script> <script src="script.js"></script>
</body> </body>
</html> </html>

View file

@ -1,14 +1,16 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<body> <body>
<link type="text/css" rel="stylesheet" href="example.css"> <link type="text/css" rel="stylesheet" href="example.css">
<form>FORM <form>FORM
<div>DIV <div>DIV
<p>P</p> <p>P</p>
</div> </div>
</form> </form>
<script src="script.js"></script> <script src="script.js"></script>
</body> </body>
</html> </html>

View file

@ -1,43 +1,44 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<link rel="stylesheet" href="messages.css"> <link rel="stylesheet" href="messages.css">
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="messages-container"> <div id="messages-container">
<div class="pane"> <div class="pane">
<h3>Лошадь</h3> <h3>Лошадь</h3>
<p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p> <p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p>
<button class="remove-button">[x]</button> <button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Осёл</h3>
<p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3>
<p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют
тёлками.</p>
<button class="remove-button">[x]</button>
</div>
</div> </div>
<div class="pane">
<h3>Осёл</h3>
<p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p>
<button class="remove-button">[x]</button>
</div>
<div class="pane">
<h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3>
<p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют тёлками.</p>
<button class="remove-button">[x]</button>
</div>
</div>
<script> <script>
var container = document.getElementById('messages-container');
var container = document.getElementById('messages-container'); container.onclick = function(event) {
if (!event.target.classList.contains('remove-button')) return;
container.onclick = function(event) { event.target.parentNode.hidden = !event.target.parentNode.hidden;
if (!event.target.classList.contains('remove-button')) return; }
</script>
event.target.parentNode.hidden = !event.target.parentNode.hidden;
}
</script>
</body> </body>
</html> </html>

View file

@ -1,28 +1,32 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<link rel="stylesheet" type="text/css" href="messages.css"> <link rel="stylesheet" type="text/css" href="messages.css">
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
Кнопка для удаления: <button class="remove-button">[x]</button> Кнопка для удаления:
<button class="remove-button">[x]</button>
<div> <div>
<div class="pane"> <div class="pane">
<h3>Лошадь</h3> <h3>Лошадь</h3>
<p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p> <p>Домашняя лошадь — животное семейства непарнокопытных, одомашненный и единственный сохранившийся подвид дикой лошади, вымершей в дикой природе, за исключением небольшой популяции лошади Пржевальского.</p>
</div> </div>
<div class="pane"> <div class="pane">
<h3>Осёл</h3> <h3>Осёл</h3>
<p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p> <p>Домашний осёл или ишак — одомашненный подвид дикого осла, сыгравший важную историческую роль в развитии хозяйства и культуры человека. Все одомашненные ослы относятся к африканским ослам.</p>
</div> </div>
<div class="pane"> <div class="pane">
<h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3> <h3>Корова, а также пара слов о диком быке, о волах и о тёлках. </h3>
<p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют тёлками.</p> <p>Коро́ва — самка домашнего быка, одомашненного подвида дикого быка, парнокопытного жвачного животного семейства полорогих. Самцы вида называются быками, молодняк — телятами, кастрированные самцы — волами. Молодых (до первой стельности) самок называют
</div> тёлками.</p>
</div> </div>
</div>
</body> </body>
</html> </html>

View file

@ -1,86 +1,89 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<style> <style>
.tree span:hover { .tree span:hover {
font-weight: bold; font-weight: bold;
} }
.tree span {
cursor: pointer; .tree span {
} cursor: pointer;
</style> }
<meta charset="utf-8"> </style>
<meta charset="utf-8">
</head> </head>
<body> <body>
<ul class="tree"> <ul class="tree">
<li>Животные <li>Животные
<ul> <ul>
<li>Млекопитающие <li>Млекопитающие
<ul> <ul>
<li>Коровы</li> <li>Коровы</li>
<li>Ослы</li> <li>Ослы</li>
<li>Собаки</li> <li>Собаки</li>
<li>Тигры</li> <li>Тигры</li>
</ul> </ul>
</li> </li>
<li>Другие <li>Другие
<ul> <ul>
<li>Змеи</li> <li>Змеи</li>
<li>Птицы</li> <li>Птицы</li>
<li>Ящерицы</li> <li>Ящерицы</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
<li>Рыбы <li>Рыбы
<ul> <ul>
<li>Аквариумные <li>Аквариумные
<ul> <ul>
<li>Гуппи</li> <li>Гуппи</li>
<li>Скалярии</li> <li>Скалярии</li>
</ul> </ul>
</li> </li>
<li>Морские <li>Морские
<ul> <ul>
<li>Морская форель</li> <li>Морская форель</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
</ul> </ul>
<script> <script>
var tree = document.getElementsByTagName('ul')[0]; var tree = document.getElementsByTagName('ul')[0];
var treeLis = tree.getElementsByTagName('li'); var treeLis = tree.getElementsByTagName('li');
/* wrap all textNodes into spans */ /* wrap all textNodes into spans */
for(var i=0; i<treeLis.length; i++) { for (var i = 0; i < treeLis.length; i++) {
var li = treeLis[i]; var li = treeLis[i];
var span = document.createElement('span'); var span = document.createElement('span');
li.insertBefore(span, li.firstChild); li.insertBefore(span, li.firstChild);
span.appendChild(span.nextSibling); span.appendChild(span.nextSibling);
} }
/* catch clicks on whole tree */ /* catch clicks on whole tree */
tree.onclick = function(event) { tree.onclick = function(event) {
var target = event.target; var target = event.target;
if (target.tagName != 'SPAN') { if (target.tagName != 'SPAN') {
return; return;
} }
/* now we know the SPAN is clicked */ /* now we know the SPAN is clicked */
var childrenContainer = target.parentNode.getElementsByTagName('ul')[0]; var childrenContainer = target.parentNode.getElementsByTagName('ul')[0];
if (!childrenContainer) return; // no children if (!childrenContainer) return; // no children
childrenContainer.hidden = !childrenContainer.hidden; childrenContainer.hidden = !childrenContainer.hidden;
} }
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,45 +1,50 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body> <body>
<ul class="tree"> <ul class="tree">
<li>Животные <li>Животные
<ul> <ul>
<li>Млекопитающие <li>Млекопитающие
<ul> <ul>
<li>Коровы</li> <li>Коровы</li>
<li>Ослы</li> <li>Ослы</li>
<li>Собаки</li> <li>Собаки</li>
<li>Тигры</li> <li>Тигры</li>
</ul> </ul>
</li> </li>
<li>Другие <li>Другие
<ul> <ul>
<li>Змеи</li> <li>Змеи</li>
<li>Птицы</li> <li>Птицы</li>
<li>Ящерицы</li> <li>Ящерицы</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
<li>Рыбы <li>Рыбы
<ul> <ul>
<li>Аквариумные <li>Аквариумные
<ul> <ul>
<li>Гуппи</li> <li>Гуппи</li>
<li>Скалярии</li> <li>Скалярии</li>
</ul> </ul>
</li> </li>
<li>Морские <li>Морские
<ul> <ul>
<li>Морская форель</li> <li>Морская форель</li>
</ul> </ul>
</li> </li>
</ul> </ul>
</li> </li>
</ul> </ul>
</body> </body>
</html> </html>

View file

@ -1,26 +1,29 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
th { th {
cursor: pointer; cursor: pointer;
} }
th:hover { th:hover {
background: yellow; background: yellow;
} }
</style> </style>
</head> </head>
<body>
<table id="grid"> <body>
<thead>
<table id="grid">
<thead>
<tr> <tr>
<th data-type="number">Возраст</th> <th data-type="number">Возраст</th>
<th data-type="string">Имя</th> <th data-type="string">Имя</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr> <tr>
<td>5</td> <td>5</td>
<td>Вася</td> <td>Вася</td>
@ -41,63 +44,63 @@
<td>1</td> <td>1</td>
<td>Илья</td> <td>Илья</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
<script> <script>
// сортировка таблицы // сортировка таблицы
// использовать делегирование! // использовать делегирование!
// должно быть масштабируемо: // должно быть масштабируемо:
// код работает без изменений при добавлении новых столбцов и строк // код работает без изменений при добавлении новых столбцов и строк
var grid = document.getElementById('grid'); var grid = document.getElementById('grid');
grid.onclick = function(e) { grid.onclick = function(e) {
if (e.target.tagName != 'TH') return; if (e.target.tagName != 'TH') return;
// Если TH -- сортируем // Если TH -- сортируем
sortGrid(e.target.cellIndex, e.target.getAttribute('data-type')); sortGrid(e.target.cellIndex, e.target.getAttribute('data-type'));
}; };
function sortGrid(colNum, type) { function sortGrid(colNum, type) {
var tbody = grid.getElementsByTagName('tbody')[0]; var tbody = grid.getElementsByTagName('tbody')[0];
// Составить массив из TR // Составить массив из TR
var rowsArray = [].slice.call(tbody.rows); var rowsArray = [].slice.call(tbody.rows);
// определить функцию сравнения, в зависимости от типа // определить функцию сравнения, в зависимости от типа
var compare; var compare;
switch(type) {
case 'number':
compare = function(rowA, rowB) {
return rowA.cells[colNum].innerHTML - rowB.cells[colNum].innerHTML;
};
break;
case 'string':
compare = function(rowA, rowB) {
return rowA.cells[colNum].innerHTML > rowB.cells[colNum].innerHTML ? 1 : -1;
};
break;
}
// сортировать
rowsArray.sort(compare);
// Убрать tbody из большого DOM документа для лучшей производительности
grid.removeChild(tbody);
// добавить результат в нужном порядке в TBODY
// они автоматически будут убраны со старых мест и вставлены в правильном порядке
for(var i=0; i<rowsArray.length; i++) {
tbody.appendChild(rowsArray[i]);
}
grid.appendChild(tbody);
switch (type) {
case 'number':
compare = function(rowA, rowB) {
return rowA.cells[colNum].innerHTML - rowB.cells[colNum].innerHTML;
};
break;
case 'string':
compare = function(rowA, rowB) {
return rowA.cells[colNum].innerHTML > rowB.cells[colNum].innerHTML ? 1 : -1;
};
break;
} }
</script> // сортировать
rowsArray.sort(compare);
// Убрать tbody из большого DOM документа для лучшей производительности
grid.removeChild(tbody);
// добавить результат в нужном порядке в TBODY
// они автоматически будут убраны со старых мест и вставлены в правильном порядке
for (var i = 0; i < rowsArray.length; i++) {
tbody.appendChild(rowsArray[i]);
}
grid.appendChild(tbody);
}
</script>
</body>
</body>
</html> </html>

View file

@ -1,26 +1,29 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head>
<head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
th { th {
cursor: pointer; cursor: pointer;
} }
th:hover { th:hover {
background: yellow; background: yellow;
} }
</style> </style>
</head> </head>
<body>
<table id="grid"> <body>
<thead>
<table id="grid">
<thead>
<tr> <tr>
<th data-type="number">Возраст</th> <th data-type="number">Возраст</th>
<th data-type="string">Имя</th> <th data-type="string">Имя</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr> <tr>
<td>5</td> <td>5</td>
<td>Вася</td> <td>Вася</td>
@ -41,13 +44,13 @@
<td>1</td> <td>1</td>
<td>Илья</td> <td>Илья</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
<script> <script>
/* ваш код */ /* ваш код */
</script>
</script> </body>
</body>
</html> </html>

View file

@ -1,66 +1,94 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<body> <body>
<link type="text/css" rel="stylesheet" href="bagua.css"> <link type="text/css" rel="stylesheet" href="bagua.css">
<table id="bagua-table"> <table id="bagua-table">
<tr> <tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th> <th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr> </tr>
<tr> <tr>
<td class="nw"><strong>Northwest</strong><br>Metal<br>Silver<br>Elders <td class="nw"><strong>Northwest</strong>
</td> <br>Metal
<td class="n"><strong>North</strong><br>Water<br>Blue<br>Change <br>Silver
</td> <br>Elders
<td class="ne"><strong>Northeast</strong><br>Earth<br>Yellow<br>Direction </td>
</td> <td class="n"><strong>North</strong>
</tr> <br>Water
<tr> <br>Blue
<td class="w"><strong>West</strong><br>Metal<br>Gold<br>Youth <br>Change
</td> </td>
<td class="c"><strong>Center</strong><br>All<br>Purple<br>Harmony <td class="ne"><strong>Northeast</strong>
</td> <br>Earth
<td class="e"><strong>East</strong><br>Wood<br>Blue<br>Future <br>Yellow
</td> <br>Direction
</tr> </td>
<tr> </tr>
<td class="sw"><strong>Southwest</strong><br>Earth<br>Brown<br>Tranquility <tr>
</td> <td class="w"><strong>West</strong>
<td class="s"><strong>South</strong><br>Fire<br>Orange<br>Fame <br>Metal
</td> <br>Gold
<td class="se"><strong>Southeast</strong><br>Wood<br>Green<br>Romance <br>Youth
</td> </td>
</tr> <td class="c"><strong>Center</strong>
<br>All
<br>Purple
<br>Harmony
</td>
<td class="e"><strong>East</strong>
<br>Wood
<br>Blue
<br>Future
</td>
</tr>
<tr>
<td class="sw"><strong>Southwest</strong>
<br>Earth
<br>Brown
<br>Tranquility
</td>
<td class="s"><strong>South</strong>
<br>Fire
<br>Orange
<br>Fame
</td>
<td class="se"><strong>Southeast</strong>
<br>Wood
<br>Green
<br>Romance
</td>
</tr>
</table> </table>
<script> <script>
var table = document.getElementById('bagua-table'); var table = document.getElementById('bagua-table');
var selectedTd; var selectedTd;
table.onclick = function(event) { table.onclick = function(event) {
var target = event.target; var target = event.target;
while(target != this) { while (target != this) {
if (target.tagName == 'TD') { if (target.tagName == 'TD') {
highlight(target); highlight(target);
return; return;
}
target = target.parentNode;
}
} }
target = target.parentNode;
}
}
function highlight(node) { function highlight(node) {
if (selectedTd) { if (selectedTd) {
selectedTd.classList.remove('highlight'); selectedTd.classList.remove('highlight');
} }
selectedTd = node; selectedTd = node;
selectedTd.classList.add('highlight'); selectedTd.classList.add('highlight');
} }
</script>
</script>
</body> </body>
</html> </html>

View file

@ -1,80 +1,81 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<style> <style>
body { body {
height: 2000px; /* подсказка должна работать независимо от прокрутки */ height: 2000px;
} /* подсказка должна работать независимо от прокрутки */
}
.tooltip { .tooltip {
position: fixed; position: fixed;
padding: 10px 20px; padding: 10px 20px;
/* красивости... */
/* красивости... */ border: 1px solid #b3c9ce;
border: 1px solid #b3c9ce; border-radius: 4px;
border-radius: 4px; text-align: center;
text-align: center; font: italic 14px/1.3 arial, sans-serif;
font: italic 14px/1.3 arial, sans-serif; color: #333;
color: #333; background: #fff;
background: #fff; box-shadow: 3px 3px 3px rgba(0, 0, 0, .3);
box-shadow: 3px 3px 3px rgba(0,0,0,.3); }
} </style>
</style>
</head> </head>
<body> <body>
<p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p> <p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p>
<p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p> <p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p>
<button data-tooltip="подсказка длиннее, чем элемент">Короткая кнопка</button> <button data-tooltip="подсказка длиннее, чем элемент">Короткая кнопка</button>
<button data-tooltip="HTML<br>подсказка">Ещё кнопка</button> <button data-tooltip="HTML<br>подсказка">Ещё кнопка</button>
<p>Прокрутите страницу, чтобы ссылки были вверху и проверьте, правильно ли показываются подсказки.</p> <p>Прокрутите страницу, чтобы ссылки были вверху и проверьте, правильно ли показываются подсказки.</p>
<script> <script>
var showingTooltip;
var showingTooltip; document.onmouseover = function(e) {
var target = e.target;
document.onmouseover = function(e) { var tooltip = target.getAttribute('data-tooltip');
var target = e.target; if (!tooltip) return;
var tooltip = target.getAttribute('data-tooltip'); var tooltipElem = document.createElement('div');
if (!tooltip) return; tooltipElem.className = 'tooltip';
tooltipElem.innerHTML = tooltip;
document.body.appendChild(tooltipElem);
var tooltipElem = document.createElement('div'); var coords = target.getBoundingClientRect();
tooltipElem.className = 'tooltip';
tooltipElem.innerHTML = tooltip;
document.body.appendChild(tooltipElem);
var coords = target.getBoundingClientRect(); var left = coords.left + (target.offsetWidth - tooltipElem.offsetWidth) / 2;
if (left < 0) left = 0; // не вылезать за левую границу окна
var left = coords.left + (target.offsetWidth - tooltipElem.offsetWidth)/2; var top = coords.top - tooltipElem.offsetHeight - 5;
if (left < 0) left = 0; // не вылезать за левую границу окна if (top < 0) { // не вылезать за верхнюю границу окна
top = coords.top + target.offsetHeight + 5;
}
var top = coords.top - tooltipElem.offsetHeight - 5; tooltipElem.style.left = left + 'px';
if (top < 0) { // не вылезать за верхнюю границу окна tooltipElem.style.top = top + 'px';
top = coords.top + target.offsetHeight + 5;
}
tooltipElem.style.left = left + 'px'; showingTooltip = tooltipElem;
tooltipElem.style.top = top + 'px'; };
showingTooltip = tooltipElem; document.onmouseout = function(e) {
};
document.onmouseout = function(e) { if (showingTooltip) {
document.body.removeChild(showingTooltip);
showingTooltip = null;
}
if (showingTooltip) { };
document.body.removeChild(showingTooltip); </script>
showingTooltip = null;
}
};
</script>
</body> </body>
</html> </html>

Some files were not shown because too many files have changed in this diff Show more