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

View file

@ -1,11 +1,13 @@
<!DOCTYPE HTML>
<html>
<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>
</html>
</html>

View file

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

View file

@ -1,67 +1,70 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="container"></div>
<div id="container"></div>
<script>
var data = {
"Рыбы":{
"Форель":{},
"Щука":{}
},
"Деревья":{
"Хвойные":{
"Лиственница":{},
"Ель":{}
<script>
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);
}
}
};
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;
}
return ul;
}
function isObjectEmpty(obj) {
for (var key in obj) {
return false;
function isObjectEmpty(obj) {
for (var key in obj) {
return false;
}
return true;
}
return true;
}
var container = document.getElementById('container');
createTree(container, data);
</script>
var container = document.getElementById('container');
createTree(container, data);
</script>
</body>
</html>
</html>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

File diff suppressed because one or more lines are too long

View file

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

View file

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

View file

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

View file

@ -1,17 +1,21 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
</head>
<body>
<h2>Уведомление</h2>
<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.
</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.
</p>
<script>
/**
* Показывает уведомление, пропадающее через 1.5 сек
@ -23,7 +27,7 @@
* @param options.html {string} HTML-текст для показа
*/
function showNotification(options) {
var notification = document.createElement('div');
notification.className = "notification";
if (options.cssText) {
@ -51,11 +55,11 @@
right: 10,
html: 'Привет ' + ++i,
className: "welcome"
});
});
}, 2000);
</script>
</body>
</html>
</html>

View file

@ -1,29 +1,33 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
</head>
<body>
<h2>Уведомление</h2>
<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.
</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.
</p>
<p>В CSS есть готовый класс notification, который можно ставить уведомлению.</p>
<script>
/**
* Показывает уведомление, пропадающее через 1.5 сек
*
* @param options.top {number} вертикальный отступ, в px
* @param options.right {number} правый отступ, в px
* @param options.cssText {string} строка стиля
* @param options.className {string} CSS-класс
* @param options.html {string} HTML-текст для показа
*/
* Показывает уведомление, пропадающее через 1.5 сек
*
* @param options.top {number} вертикальный отступ, в px
* @param options.right {number} правый отступ, в px
* @param options.cssText {string} строка стиля
* @param options.className {string} CSS-класс
* @param options.html {string} HTML-текст для показа
*/
function showNotification(options) {
// ваш код
}
@ -36,11 +40,11 @@
right: 10,
html: 'Привет ' + ++i,
className: "welcome"
});
});
}, 2000);
</script>
</body>
</html>
</html>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,24 +1,26 @@
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8"></head>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="elem" style="overflow-y:scroll;width:300px;height:200px;border:1px solid black">
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
</div>
<div id="elem" style="overflow-y:scroll;width:300px;height:200px;border:1px solid black">
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст текст
текст текст текст текст текст текст текст текст текст текст текст текст текст текст
</div>
<script>
// FF: 200, Ch/Sa: 184, Op: 200, IE9: 184, IE7,8:200
</script>
<script>
// FF: 200, Ch/Sa: 184, Op: 200, IE9: 184, IE7,8:200
</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>
</html>
</html>

View file

@ -1,91 +1,94 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#example {
width: 300px;
height: 200px;
overflow: auto;
border: 25px solid #E8C48F;
padding: 20px;
}
.key {
cursor: pointer;
text-decoration: underline;
}
</style>
<head>
<meta charset="utf-8">
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#example {
width: 300px;
height: 200px;
overflow: auto;
border: 25px solid #E8C48F;
padding: 20px;
}
.key {
cursor: pointer;
text-decoration: underline;
}
</style>
</head>
<body>
<div id="example">
<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>
<div id="example">
<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>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="info"></div>
<div id="mouse-wrap">Координаты мыши: <span id="mouse">...</span></div>
<div id="info"></div>
<script>
var example = document.getElementById('example')
<script>
var example = document.getElementById('example')
var info = document.getElementById('info')
var info = document.getElementById('info')
var props = {
'размеры':
['clientLeft','clientTop', 'clientWidth','clientHeight','offsetWidth','offsetHeight','scrollWidth', 'scrollHeight'],
'прокрутка':
['scrollLeft','scrollTop'] ,
'позиционирование по рендерингу':
['offsetParent', 'offsetLeft','offsetTop']
}
var props = {
'размеры': ['clientLeft', 'clientTop', 'clientWidth', 'clientHeight', 'offsetWidth', 'offsetHeight', 'scrollWidth', 'scrollHeight'],
'прокрутка': ['scrollLeft', 'scrollTop'],
'позиционирование по рендерингу': ['offsetParent', 'offsetLeft', 'offsetTop']
}
info.innerHTML = '<h3>Нажмите для просмотра значения:</h3>';
for (var k in props) {
info.innerHTML += '<h4>' + k + '</h4>';
var prop = props[k];
for (var i = 0; i < prop.length; i++) {
info.innerHTML += "<span class='key'>"+prop[i]+'</span>: <span id="'+prop[i]+'">&nbsp;</span>' + " "
info.innerHTML = '<h3>Нажмите для просмотра значения:</h3>';
for (var k in props) {
info.innerHTML += '<h4>' + k + '</h4>';
var prop = props[k];
for (var i = 0; i < prop.length; i++) {
info.innerHTML += "<span class='key'>" + prop[i] + '</span>: <span id="' + prop[i] + '">&nbsp;</span>' + " "
i++;
if (i<prop.length) {
info.innerHTML += "<span class='key'>"+prop[i]+'</span>: <span id="'+prop[i]+'">&nbsp;</span>';
if (i < prop.length) {
info.innerHTML += "<span class='key'>" + prop[i] + '</span>: <span id="' + prop[i] + '">&nbsp;</span>';
}
info.innerHTML += "<br/>";
}
}
}
document.onclick = function(event) {
var target = event.target;
if (!target.classList.contains('key')) return;
document.onclick = function(event) {
var target = event.target;
if (!target.classList.contains('key')) return;
var prop = target.innerHTML;
var value = example[prop];
value = value.tagName || value;
document.getElementById(prop).innerHTML = value;
};
var prop = target.innerHTML;
var value = example[prop];
value = value.tagName || value;
document.getElementById(prop).innerHTML = value;
};
document.onmousemove = function(e) {
document.getElementById('mouse').innerHTML = Math.round(e.clientX)+':'+Math.round(e.clientY);
};
</script>
document.onmousemove = function(e) {
document.getElementById('mouse').innerHTML = Math.round(e.clientX) + ':' + Math.round(e.clientY);
};
</script>
</body>
</html>
</html>

View file

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

View file

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

View file

@ -1,30 +1,26 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
</head>
<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>
<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>
<script>
<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>
<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>
<script>
/**
* Позиционирует элемент elem относительно элемента anchor, как указано в
* в position.
@ -39,21 +35,21 @@
var anchorCoords = anchor.getBoundingClientRect();
switch(position) {
case "top":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break;
switch (position) {
case "top":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break;
case "right":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "right":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "bottom":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break;
case "bottom":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break;
}
}
@ -63,11 +59,11 @@
* относительно элемента anchor
*/
function showNote(anchor, position, html) {
var note = document.createElement('div');
note.className = "note";
note.innerHTML = html;
document.body.appendChild(note);
document.body.appendChild(note);
positionAt(anchor, position, note);
}
@ -82,4 +78,5 @@
</body>
</html>
</html>

View file

@ -1,30 +1,26 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
</head>
<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>
<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>
<script>
<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>
<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>
<script>
/**
* Позиционирует элемент elem относительно элемента anchor, как указано в
* в position.
@ -55,4 +51,5 @@
</body>
</html>
</html>

View file

@ -1,54 +1,52 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
</head>
<body style="height:2000px">
<p>Исправления два:</p>
<ol>
<li>Использование функции <code>getCoords()</code> из учебника для получения абсолютных координат.</li>
<li>Изменение <code>position:fixed</code> на <code>position:absolute</code> в стилях.</li>
</ol>
<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>
<script>
<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>
<script>
/**
* Вспомогательная функция для координат относительно документа
*/
function getCoords(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 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;
return { top: top, left: left };
return {
top: top,
left: left
};
}
@ -56,21 +54,21 @@
var anchorCoords = getCoords(anchor);
switch(position) {
case "top":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break;
switch (position) {
case "top":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break;
case "right":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "right":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "bottom":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break;
case "bottom":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break;
}
}
@ -80,11 +78,11 @@
* относительно элемента anchor
*/
function showNote(anchor, position, html) {
var note = document.createElement('div');
note.className = "note";
note.innerHTML = html;
document.body.appendChild(note);
document.body.appendChild(note);
positionAt(anchor, position, note);
}
@ -98,4 +96,5 @@
</body>
</html>
</html>

View file

@ -1,53 +1,53 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
</head>
<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>
<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>
function getCoords(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 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;
return { top: top, left: left };
return {
top: top,
left: left
};
}
function showNote(anchor, position, html) {
var note = document.createElement('div');
note.className = "note";
note.innerHTML = html;
document.body.appendChild(note);
document.body.appendChild(note);
positionAt(anchor, position, note);
}
@ -66,36 +66,36 @@
var anchorCoords = getCoords(anchor);
switch(position) {
case "top-out":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break;
switch (position) {
case "top-out":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top - elem.offsetHeight + "px";
break;
case "right-out":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "right-out":
elem.style.left = anchorCoords.left + anchor.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "bottom-out":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break;
case "bottom-out":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight + "px";
break;
case "top-in":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "top-in":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "right-in":
elem.style.left = anchorCoords.left + anchor.offsetWidth - elem.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "right-in":
elem.style.left = anchorCoords.left + anchor.offsetWidth - elem.offsetWidth + "px";
elem.style.top = anchorCoords.top + "px";
break;
case "bottom-in":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight - elem.offsetHeight + "px";
break;
case "bottom-in":
elem.style.left = anchorCoords.left + "px";
elem.style.top = anchorCoords.top + anchor.offsetHeight - elem.offsetHeight + "px";
break;
}
}
@ -107,9 +107,9 @@
showNote(blockquote, "top-out", "заметка top-out");
showNote(blockquote, "right-out", "заметка right-out");
showNote(blockquote, "bottom-in", "заметка bottom-in");
</script>
</body>
</html>
</html>

View file

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

View file

@ -1,28 +1,66 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
table { border-collapse: collapse; }
td { border: 1px solid black; padding: 3px 5px; }
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 3px 5px;
}
</style>
</head>
<body>
<table>
<tr><td>1:1</td><td>2:1</td><td>3:1</td><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>
<tr>
<td>1:1</td>
<td>2:1</td>
<td>3:1</td>
<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>
<script>
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];
row.cells[i].style.backgroundColor = 'red';
}
</script>
</body>
</html>
</html>

View file

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

View file

@ -1,42 +1,48 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form name="search">
<label>Поиск по сайту: <input type="text" name="search"></label>
<input type="submit" value="Искать!">
</form>
<hr>
<form name="search-person">
Поиск по посетителям:
<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>
<td>Дополнительно:</td>
<td>
<input type="text" name="info[0]">
<input type="text" name="info[1]">
<input type="text" name="info[2]">
</td>
</tr>
</table>
<input type="submit" value="Искать!">
</form>
</body>
<head>
<meta charset="utf-8">
</head>
<body>
<form name="search">
<label>Поиск по сайту:
<input type="text" name="search">
</label>
<input type="submit" value="Искать!">
</form>
<hr>
<form name="search-person">
Поиск по посетителям:
<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>
<td>Дополнительно:</td>
<td>
<input type="text" name="info[0]">
<input type="text" name="info[1]">
<input type="text" name="info[2]">
</td>
</tr>
</table>
<input type="submit" value="Искать!">
</form>
</body>
</html>

View file

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

View file

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

View file

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

View file

@ -1,32 +1,170 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta charset="utf-8">
</head>
<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>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>
<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>
<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>
</html>
</html>

View file

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

View file

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

View file

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

View file

@ -1,16 +1,19 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<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>
</html>
</html>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,18 +1,21 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="example.css">
</head>
<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
<p>P</p>
<p>P</p>
</div>
</form>
</form>
<script src="script.js"></script>
<script src="script.js"></script>
</body>
</html>
</html>

View file

@ -1,14 +1,16 @@
<!DOCTYPE HTML>
<html>
<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
<p>P</p>
<p>P</p>
</div>
</form>
</form>
<script src="script.js"></script>
<script src="script.js"></script>
</body>
</html>
</html>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,66 +1,94 @@
<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="bagua.css">
<link type="text/css" rel="stylesheet" href="bagua.css">
<table id="bagua-table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong><br>Metal<br>Silver<br>Elders
</td>
<td class="n"><strong>North</strong><br>Water<br>Blue<br>Change
</td>
<td class="ne"><strong>Northeast</strong><br>Earth<br>Yellow<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong><br>Metal<br>Gold<br>Youth
</td>
<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 id="bagua-table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong>
<br>Metal
<br>Silver
<br>Elders
</td>
<td class="n"><strong>North</strong>
<br>Water
<br>Blue
<br>Change
</td>
<td class="ne"><strong>Northeast</strong>
<br>Earth
<br>Yellow
<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong>
<br>Metal
<br>Gold
<br>Youth
</td>
<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>
<script>
var table = document.getElementById('bagua-table');
</table>
var selectedTd;
<script>
var table = document.getElementById('bagua-table');
table.onclick = function(event) {
var target = event.target;
while(target != this) {
if (target.tagName == 'TD') {
highlight(target);
return;
var selectedTd;
table.onclick = function(event) {
var target = event.target;
while (target != this) {
if (target.tagName == 'TD') {
highlight(target);
return;
}
target = target.parentNode;
}
}
target = target.parentNode;
}
}
function highlight(node) {
if (selectedTd) {
selectedTd.classList.remove('highlight');
}
selectedTd = node;
selectedTd.classList.add('highlight');
}
</script>
function highlight(node) {
if (selectedTd) {
selectedTd.classList.remove('highlight');
}
selectedTd = node;
selectedTd.classList.add('highlight');
}
</script>
</body>
</html>
</html>

View file

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

View file

@ -1,32 +1,32 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
height: 2000px; /* подсказка должна работать независимо от прокрутки */
}
/* ваши стили */
</style>
<meta charset="utf-8">
<style>
body {
height: 2000px;
/* подсказка должна работать независимо от прокрутки */
}
/* ваши стили */
</style>
</head>
<body>
<p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p>
<p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p>
<p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p>
<p>ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя ЛяЛяЛя</p>
<button data-tooltip="подсказка длиннее, чем элемент">Короткая кнопка</button>
<button data-tooltip="HTML<br>подсказка">Ещё кнопка</button>
<button data-tooltip="подсказка длиннее, чем элемент">Короткая кнопка</button>
<button data-tooltip="HTML<br>подсказка">Ещё кнопка</button>
<p>Прокрутите страницу, чтобы ссылки были вверху и проверьте, правильно ли показываются подсказки.</p>
<p>Прокрутите страницу, чтобы ссылки были вверху и проверьте, правильно ли показываются подсказки.</p>
<script>
// ваш код
</script>
<script>
// ваш код
</script>
</body>
</html>
</html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
@ -9,32 +10,34 @@
}
</style>
</head>
<body>
<fieldset id="contents">
<legend>#contents</legend>
<p>
Как насчет почитать <a href="http://wikipedia.org">Википедию</a>, или посетить <a href="http://w3.org"><i>W3.org</i></a> и узнать про современные стандарты?
</p>
</fieldset>
<fieldset id="contents">
<legend>#contents</legend>
<p>
Как насчет почитать <a href="http://wikipedia.org">Википедию</a>, или посетить <a href="http://w3.org"><i>W3.org</i></a> и узнать про современные стандарты?
</p>
</fieldset>
<script>
document.getElementById('contents').onclick = function(event) {
<script>
document.getElementById('contents').onclick = function(event) {
function handleLink(href) {
var isLeaving = confirm('Уйти на '+href+'?');
if (!isLeaving) return false;
}
var target = event.target;
while(target != this) {
if (target.nodeName == 'A') {
return handleLink(target.getAttribute('href'));
function handleLink(href) {
var isLeaving = confirm('Уйти на ' + href + '?');
if (!isLeaving) return false;
}
var target = event.target;
while (target != this) {
if (target.nodeName == 'A') {
return handleLink(target.getAttribute('href'));
}
target = target.parentNode;
}
target = target.parentNode;
}
}
</script>
</script>
</body>
</html>
</html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
@ -9,14 +10,16 @@
}
</style>
</head>
<body>
<fieldset id="contents">
<legend>#contents</legend>
<p>
Как насчет почитать <a href="http://wikipedia.org">Википедию</a>, или посетить <a href="http://w3.org"><i>W3.org</i></a> и узнать про современные стандарты?
</p>
</fieldset>
<fieldset id="contents">
<legend>#contents</legend>
<p>
Как насчет почитать <a href="http://wikipedia.org">Википедию</a>, или посетить <a href="http://w3.org"><i>W3.org</i></a> и узнать про современные стандарты?
</p>
</fieldset>
</body>
</html>
</html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Галерея</title>
<link rel="stylesheet" href="gallery.css">
@ -8,51 +9,62 @@
<body>
<p><img id="largeImg" src="https://js.cx/gallery/img1-lg.jpg" alt="Large image"></p>
<p><img id="largeImg" src="https://js.cx/gallery/img1-lg.jpg" alt="Large image"></p>
<ul id="thumbs">
<!-- При наведении на изображение показывается встроенная подсказка браузера (title) -->
<li><a href="https://js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://js.cx/gallery/img2-thumb.jpg"></a></li>
<li><a href="https://js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://js.cx/gallery/img3-thumb.jpg"></a></li>
<li><a href="https://js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://js.cx/gallery/img4-thumb.jpg"></a></li>
<li><a href="https://js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://js.cx/gallery/img5-thumb.jpg"></a></li>
<li><a href="https://js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://js.cx/gallery/img6-thumb.jpg"></a></li>
</ul>
<ul id="thumbs">
<!-- При наведении на изображение показывается встроенная подсказка браузера (title) -->
<li>
<a href="https://js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://js.cx/gallery/img2-thumb.jpg"></a>
</li>
<li>
<a href="https://js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://js.cx/gallery/img3-thumb.jpg"></a>
</li>
<li>
<a href="https://js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://js.cx/gallery/img4-thumb.jpg"></a>
</li>
<li>
<a href="https://js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://js.cx/gallery/img5-thumb.jpg"></a>
</li>
<li>
<a href="https://js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://js.cx/gallery/img6-thumb.jpg"></a>
</li>
</ul>
<script>
var largeImg = document.getElementById('largeImg');
<script>
var largeImg = document.getElementById('largeImg');
var thumbs = document.getElementById('thumbs');
var thumbs = document.getElementById('thumbs');
thumbs.onclick = function(e) {
var target = e.target;
thumbs.onclick = function(e) {
var target = e.target;
while(target != this) {
while (target != this) {
if (target.nodeName == 'A') {
showThumbnail(target.href, target.title);
return false;
}
target = target.parentNode;
}
if (target.nodeName == 'A') {
showThumbnail(target.href, target.title);
return false;
}
target = target.parentNode;
}
}
function showThumbnail(href, title) {
largeImg.src = href;
largeImg.alt = title;
}
function showThumbnail(href, title) {
largeImg.src = href;
largeImg.alt = title;
}
/* предзагрузка */
var imgs = thumbs.getElementsByTagName('img');
for(var i=0; i<imgs.length; i++) {
var url = imgs[i].parentNode.href;
var img = document.createElement('img');
img.src = url;
}
</script>
/* предзагрузка */
var imgs = thumbs.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var url = imgs[i].parentNode.href;
var img = document.createElement('img');
img.src = url;
}
</script>
</body>
</html>
</html>

View file

@ -1,5 +1,6 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Галерея</title>
<link rel="stylesheet" href="gallery.css">
@ -8,16 +9,17 @@
<body>
<p><img id="largeImg" src="https://js.cx/gallery/img1-lg.jpg" alt="Large image"></p>
<p><img id="largeImg" src="https://js.cx/gallery/img1-lg.jpg" alt="Large image"></p>
<div id="thumbs">
<!-- При наведении на изображение показывается встроенная подсказка браузера (title) -->
<a href="https://js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://js.cx/gallery/img2-thumb.jpg"></a>
<a href="https://js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://js.cx/gallery/img3-thumb.jpg"></a>
<a href="https://js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://js.cx/gallery/img4-thumb.jpg"></a>
<a href="https://js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://js.cx/gallery/img5-thumb.jpg"></a>
<a href="https://js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://js.cx/gallery/img6-thumb.jpg"></a>
</div>
<div id="thumbs">
<!-- При наведении на изображение показывается встроенная подсказка браузера (title) -->
<a href="https://js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://js.cx/gallery/img2-thumb.jpg"></a>
<a href="https://js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://js.cx/gallery/img3-thumb.jpg"></a>
<a href="https://js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://js.cx/gallery/img4-thumb.jpg"></a>
<a href="https://js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://js.cx/gallery/img5-thumb.jpg"></a>
<a href="https://js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://js.cx/gallery/img6-thumb.jpg"></a>
</div>
</body>
</html>
</html>

View file

@ -1,19 +1,22 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="menu.css"/>
<link rel="stylesheet" href="menu.css" />
</head>
<body>
<ul id="menu" class="menu">
<li><a href="/php">PHP</a></li>
<li><a href="/html">HTML</a></li>
<li><a href="/javascript">JavaScript</a></li>
<li><a href="/flash">Flash</a></li>
</ul>
<ul id="menu" class="menu">
<li><a href="/php">PHP</a></li>
<li><a href="/html">HTML</a></li>
<li><a href="/javascript">JavaScript</a></li>
<li><a href="/flash">Flash</a></li>
</ul>
<script src="menu.js"></script>
<script src="menu.js"></script>
</body>
</html>
</html>

View file

@ -1,98 +1,100 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
.selected {
background: #0f0;
}
li {
cursor: pointer;
}
</style>
</head>
<body>
Клик на элементе выделяет только его.<br>
Ctrl(Cmd)+Клик добавляет/убирает элемент из выделенных.<br>
Shift+Клик добавляет промежуток от последнего кликнутого к выделению.<br>
Клик на элементе выделяет только его.
<br> Ctrl(Cmd)+Клик добавляет/убирает элемент из выделенных.
<br> Shift+Клик добавляет промежуток от последнего кликнутого к выделению.
<br>
<ul>
<li>Кристофер Робин</li>
<li>Винни-Пух</li>
<li>Ослик Иа</li>
<li>Мудрая Сова</li>
<li>Кролик. Просто кролик.</li>
</ul>
<ul>
<li>Кристофер Робин</li>
<li>Винни-Пух</li>
<li>Ослик Иа</li>
<li>Мудрая Сова</li>
<li>Кролик. Просто кролик.</li>
</ul>
<script>
<script>
var ul = document.querySelector('ul');
var ul = document.querySelector('ul');
var lastClickedLi = null;
var lastClickedLi = null;
// --- обработчики ---
// --- обработчики ---
ul.onclick = function(event) {
var target = event.target;
ul.onclick = function(event) {
var target = event.target;
// возможно, клик был внутри списка UL, но вне элементов LI
if (target.tagName != "LI") return;
// возможно, клик был внутри списка UL, но вне элементов LI
if (target.tagName != "LI") return;
// для Mac проверяем Cmd, т.к. Ctrl + click там контекстное меню
if (event.metaKey || event.ctrlKey) {
toggleSelect(target);
} else if (event.shiftKey) {
selectFromLast(target);
} else {
selectSingle(target);
}
// для Mac проверяем Cmd, т.к. Ctrl + click там контекстное меню
if(event.metaKey || event.ctrlKey) {
toggleSelect(target);
} else if (event.shiftKey) {
selectFromLast(target);
} else {
selectSingle(target);
}
lastClickedLi = target;
}
lastClickedLi = target;
}
ul.onmousedown = function() {
return false;
};
ul.onmousedown = function() {
return false;
};
// --- функции для выделения ---
// --- функции для выделения ---
function toggleSelect(li) {
li.classList.toggle('selected');
}
function toggleSelect(li) {
li.classList.toggle('selected');
}
function selectFromLast(target) {
var startElem = lastClickedLi || ul.children[0];
function selectFromLast(target) {
var startElem = lastClickedLi || ul.children[0];
var isLastClickedBefore = startElem.compareDocumentPosition(target) & 4;
var isLastClickedBefore = startElem.compareDocumentPosition(target) & 4;
if (isLastClickedBefore) {
for(var elem = startElem; elem != target; elem = elem.nextElementSibling) {
if (isLastClickedBefore) {
for (var elem = startElem; elem != target; elem = elem.nextElementSibling) {
elem.classList.add('selected');
}
} else {
for (var elem = startElem; elem != target; elem = elem.previousElementSibling) {
elem.classList.add('selected');
}
}
elem.classList.add('selected');
}
} else {
for(var elem = startElem; elem != target; elem = elem.previousElementSibling) {
elem.classList.add('selected');
function deselectAll() {
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].classList.remove('selected');
}
}
}
elem.classList.add('selected');
}
function deselectAll() {
for(var i=0; i<ul.children.length; i++) {
ul.children[i].classList.remove('selected');
}
}
function selectSingle(li) {
deselectAll();
li.classList.add('selected');
}
</script>
function selectSingle(li) {
deselectAll();
li.classList.add('selected');
}
</script>
</body>
</html>
</html>

View file

@ -1,33 +1,38 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
.selected {
background: #0f0;
}
li {
cursor: pointer;
}
</style>
</head>
<body>
Клик на элементе выделяет только его.<br>
Ctrl(Cmd)+Клик добавляет/убирает элемент из выделенных.<br>
Shift+Клик добавляет промежуток от последнего кликнутого к выделению.<br>
Клик на элементе выделяет только его.
<br> Ctrl(Cmd)+Клик добавляет/убирает элемент из выделенных.
<br> Shift+Клик добавляет промежуток от последнего кликнутого к выделению.
<br>
<ul>
<li>Кристофер Робин</li>
<li>Винни-Пух</li>
<li>Ослик Иа</li>
<li>Мудрая Сова</li>
<li>Кролик. Просто кролик.</li>
</ul>
<ul>
<li>Кристофер Робин</li>
<li>Винни-Пух</li>
<li>Ослик Иа</li>
<li>Мудрая Сова</li>
<li>Кролик. Просто кролик.</li>
</ul>
<script>
// ... ваш код
</script>
<script>
// ... ваш код
</script>
</body>
</html>
</html>

View file

@ -1,92 +1,94 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
.tree li {
cursor: pointer;
}
</style>
<meta charset="utf-8">
<style>
.tree li {
cursor: pointer;
}
</style>
</head>
<body>
<ul class="tree" id="tree">
<ul class="tree" id="tree">
<li>Животные
<ul>
<li>Млекопитающие
<ul>
<li>Коровы</li>
<li>Ослы</li>
<li>Собаки</li>
<li>Тигры</li>
</ul>
</li>
<li>Другие
<ul>
<li>Змеи</li>
<li>Птицы</li>
<li>Ящерицы</li>
</ul>
</li>
</ul>
<ul>
<li>Млекопитающие
<ul>
<li>Коровы</li>
<li>Ослы</li>
<li>Собаки</li>
<li>Тигры</li>
</ul>
</li>
<li>Другие
<ul>
<li>Змеи</li>
<li>Птицы</li>
<li>Ящерицы</li>
</ul>
</li>
</ul>
</li>
<li>Рыбы
<ul>
<li>Аквариумные
<ul>
<li>Гуппи</li>
<li>Скалярии</li>
</ul>
<ul>
<li>Аквариумные
<ul>
<li>Гуппи</li>
<li>Скалярии</li>
</ul>
</li>
<li>Морские
<ul>
<li>Морская форель</li>
</ul>
</li>
</ul>
</li>
<li>Морские
<ul>
<li>Морская форель</li>
</ul>
</li>
</ul>
</li>
</ul>
</ul>
<script>
var tree = document.getElementById('tree');
<script>
var tree = document.getElementById('tree');
/* проверить на попадание события в заголовок LI */
function isOverTitle(evt, li) {
/* обернуть заголовок в span */
var titleWrapper = document.createElement('span');
var titleTextNode = li.firstChild; // <li>TITLE...
li.insertBefore(titleWrapper, titleTextNode); // <li><span></span>TITLE
titleWrapper.appendChild(titleTextNode); // <li><span>TITLE</span>
/* проверить на попадание события в заголовок LI */
function isOverTitle(evt, li) {
/* обернуть заголовок в span */
var titleWrapper = document.createElement('span');
var titleTextNode = li.firstChild; // <li>TITLE...
li.insertBefore(titleWrapper, titleTextNode); // <li><span></span>TITLE
titleWrapper.appendChild(titleTextNode); // <li><span>TITLE</span>
/* определить, был ли клик по координатам - в SPAN ?*/
var isClickOnTitle = (document.elementFromPoint(evt.clientX, evt.clientY) == titleWrapper);
/* определить, был ли клик по координатам - в SPAN ?*/
var isClickOnTitle = (document.elementFromPoint(evt.clientX, evt.clientY) == titleWrapper);
/* в любом случае вернуть заголовок в текст обратно перед тем как идти дальше */
titleWrapper.removeChild(titleWrapper.firstChild); // <li><span></span>
li.replaceChild(titleTextNode, titleWrapper); // <li>TITLE...
/* в любом случае вернуть заголовок в текст обратно перед тем как идти дальше */
titleWrapper.removeChild(titleWrapper.firstChild); // <li><span></span>
li.replaceChild(titleTextNode, titleWrapper); // <li>TITLE...
return isClickOnTitle;
}
return isClickOnTitle;
}
/* отслеживаем клики на всём дереве */
tree.onclick = function(evt) {
var evt = evt || event;
var target = evt.target || evt.srcElement;
/* отслеживаем клики на всём дереве */
tree.onclick = function(evt) {
var evt = evt || event;
var target = evt.target || evt.srcElement;
if (!isOverTitle(evt, target)) {
return; // клик не на заголовке
}
if (!isOverTitle(evt, target)) {
return; // клик не на заголовке
}
/* раскрыть-закрыть детей */
var node = target.getElementsByTagName('ul')[0];
if (!node) return; // нет детей
/* раскрыть-закрыть детей */
var node = target.getElementsByTagName('ul')[0];
if (!node) return; // нет детей
node.style.display = node.style.display ? '' : 'none';
}
</script>
node.style.display = node.style.display ? '' : 'none';
}
</script>
</body>
</html>
</html>

View file

@ -1,68 +1,70 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
.tree li {
cursor: pointer;
}
</style>
<meta charset="utf-8">
<style>
.tree li {
cursor: pointer;
}
</style>
</head>
<body>
<ul class="tree" id="tree">
<ul class="tree" id="tree">
<li>Животные
<ul>
<li>Млекопитающие
<ul>
<li>Коровы</li>
<li>Ослы</li>
<li>Собаки</li>
<li>Тигры</li>
</ul>
</li>
<li>Другие
<ul>
<li>Змеи</li>
<li>Птицы</li>
<li>Ящерицы</li>
</ul>
</li>
</ul>
<ul>
<li>Млекопитающие
<ul>
<li>Коровы</li>
<li>Ослы</li>
<li>Собаки</li>
<li>Тигры</li>
</ul>
</li>
<li>Другие
<ul>
<li>Змеи</li>
<li>Птицы</li>
<li>Ящерицы</li>
</ul>
</li>
</ul>
</li>
<li>Рыбы
<ul>
<li>Аквариумные
<ul>
<li>Гуппи</li>
<li>Скалярии</li>
</ul>
<ul>
<li>Аквариумные
<ul>
<li>Гуппи</li>
<li>Скалярии</li>
</ul>
</li>
<li>Морские
<ul>
<li>Морская форель</li>
</ul>
</li>
</ul>
</li>
<li>Морские
<ul>
<li>Морская форель</li>
</ul>
</li>
</ul>
</li>
</ul>
</ul>
<script>
var tree = document.getElementById('tree');
<script>
var tree = document.getElementById('tree');
tree.onclick = function(evt) {
var evt = evt || event;
var target = evt.target || evt.srcElement;
tree.onclick = function(evt) {
var evt = evt || event;
var target = evt.target || evt.srcElement;
/* раскрыть-закрыть детей */
var node = target.getElementsByTagName('ul')[0];
if (!node) return; // нет детей
/* раскрыть-закрыть детей */
var node = target.getElementsByTagName('ul')[0];
if (!node) return; // нет детей
node.style.display = node.style.display ? '' : 'none';
}
</script>
node.style.display = node.style.display ? '' : 'none';
}
</script>
</body>
</html>
</html>

View file

@ -1,19 +1,22 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function setHandler() {
window.onbeforeunload = function() {
return "Данные не сохранены. Точно перейти?";
};
}
</script>
<script>
function setHandler() {
window.onbeforeunload = function() {
return "Данные не сохранены. Точно перейти?";
};
}
</script>
<button onclick="setHandler()">Поставить window.onbeforeunload</button>
<button onclick="setHandler()">Поставить window.onbeforeunload</button>
<a href="http://example.com">Уйти на EXAMPLE.COM</a>
<a href="http://example.com">Уйти на EXAMPLE.COM</a>
</body>
</html>
</html>

View file

@ -1,42 +1,49 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style> .img-replace { float: left; border: 1px solid black;} </style>
<style>
.img-replace {
float: left;
border: 1px solid black;
}
</style>
</head>
<body>
<button onclick="window.location.reload(true)">Перезагрузить ифрейм</button>
<hr>
<div style="width:114px;height:40px;font-size:32px;letter-spacing:3px" data-src="https://js.cx/search/google.png" class="img-replace">
<span style="color:#1A53F7">G</span><span style="color:#E42131">o</span><span style="color:#FEB819">o</span><span style="color:#164AF2">g</span><span style="color:#00a315">l</span><span style="color:#E42131">e</span>
</div>
<button onclick="window.location.reload(true)">Перезагрузить ифрейм</button>
<hr>
<div style="width:114px;height:40px;font-size:32px;letter-spacing:3px" data-src="https://js.cx/search/google.png" class="img-replace">
<span style="color:#1A53F7">G</span><span style="color:#E42131">o</span><span style="color:#FEB819">o</span><span style="color:#164AF2">g</span><span style="color:#00a315">l</span><span style="color:#E42131">e</span>
</div>
<div style="width:101px;height:40px;font-size:32px" data-src="https://js.cx/search/yandex.png" class="img-replace">
<span style="color:#F00">Я</span>ндекс
</div>
<div style="width:101px;height:40px;font-size:32px" data-src="https://js.cx/search/yandex.png" class="img-replace">
<span style="color:#F00">Я</span>ндекс
</div>
<div style="width:100;height:40px;font-size:32px;color:#006dd4;font-weight:bold;letter-spacing:3px;font-family:Arial" data-src="bing.png" class="img-replace">bing</div>
<div style="width:100;height:40px;font-size:32px;color:#006dd4;font-weight:bold;letter-spacing:3px;font-family:Arial" data-src="bing.png" class="img-replace">bing</div>
<script>
<script>
function replaceImg() {
var divs = document.querySelectorAll('div.img-replace');
for (var i = 0; i < divs.length; i++)(function(i) {
var img = document.createElement('img');
img.src = divs[i].getAttribute('data-src');
img.className = 'img-replace';
function replaceImg() {
var divs = document.querySelectorAll('div.img-replace');
for(var i=0; i<divs.length; i++) (function(i) {
var img = document.createElement('img');
img.src = divs[i].getAttribute('data-src');
img.className = 'img-replace';
img.onload = function() {
divs[i].parentNode.replaceChild(img, divs[i]);
}
img.onload = function() {
divs[i].parentNode.replaceChild(img, divs[i]);
}(i))
}
}(i))
}
setTimeout(replaceImg, 1000); // задержка на 1 сек для демонстрации
</script>
setTimeout(replaceImg, 1000); // задержка на 1 сек для демонстрации
</script>
</body>
</html>
</html>

View file

@ -1,32 +1,40 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style> .img-replace { float: left; border: 1px solid black;} </style>
<style>
.img-replace {
float: left;
border: 1px solid black;
}
</style>
</head>
<body>
<!-- Google -->
<!-- Google -->
<div style="width:114px;height:40px;font-size:32px;letter-spacing:3px" class="img-replace">
<span style="color:#1A53F7">G</span><span style="color:#E42131">o</span><span style="color:#FEB819">o</span><span style="color:#164AF2">g</span><span style="color:#00a315">l</span><span style="color:#E42131">e</span>
</div>
<div style="width:114px;height:40px;font-size:32px;letter-spacing:3px" class="img-replace">
<span style="color:#1A53F7">G</span><span style="color:#E42131">o</span><span style="color:#FEB819">o</span><span style="color:#164AF2">g</span><span style="color:#00a315">l</span><span style="color:#E42131">e</span>
</div>
<!-- Яндекс -->
<div style="width:101px;height:40px;font-size:32px" class="img-replace">
<span style="color:#F00">Я</span>ндекс
</div>
<!-- Яндекс -->
<div style="width:101px;height:40px;font-size:32px" class="img-replace">
<span style="color:#F00">Я</span>ндекс
</div>
<!-- Bing -->
<div style="width:100;height:40px;font-size:32px;color:#006dd4;font-weight:bold;letter-spacing: 3px; font-family:Arial">bing</div>
<!-- Bing -->
<div style="width:100;height:40px;font-size:32px;color:#006dd4;font-weight:bold;letter-spacing: 3px; font-family:Arial">bing</div>
<hr>
<!-- картинки (для bing картинки специально нет, чтобы протестировать случай "загрузка не удалась") -->
<hr>
<!-- картинки (для bing картинки специально нет, чтобы протестировать случай "загрузка не удалась") -->
<img src="https://js.cx/search/yandex.png" width="114" height="40" alt="Яндекс">
<img src="https://js.cx/search/google.png" width="101" height="40" alt="Google">
<img src="https://js.cx/search/bing.png" width="101" height="40" alt="Файла нет (bing)">
<img src="https://js.cx/search/yandex.png" width="114" height="40" alt="Яндекс">
<img src="https://js.cx/search/google.png" width="101" height="40" alt="Google">
<img src="https://js.cx/search/bing.png" width="101" height="40" alt="Файла нет (bing)">
</body>
</html>
</html>

View file

@ -1,56 +1,57 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
<script>
function preloadImages(sources, callback) {
var counter = 0;
function preloadImages(sources, callback) {
var counter = 0;
function onLoad() {
counter++;
if (counter == sources.length) callback();
}
for (var i = 0; i < sources.length; i++) {
var img = document.createElement('img');
// сначала onload/onerror, затем src - важно для IE8-
img.onload = img.onerror = onLoad;
img.src = sources[i];
}
function onLoad() {
counter++;
if (counter == sources.length) callback();
}
// ---------- Проверка ----------
var sources = [
"https://js.cx/images-load/1.jpg",
"https://js.cx/images-load/2.jpg",
"https://js.cx/images-load/3.jpg"
];
for (var i = 0; i < sources.length; i++) {
var img = document.createElement('img');
// сначала onload/onerror, затем src - важно для IE8-
img.onload = img.onerror = onLoad;
img.src = sources[i];
sources[i] += '?' + Math.random();
}
}
// ---------- Проверка ----------
var sources = [
"https://js.cx/images-load/1.jpg",
"https://js.cx/images-load/2.jpg",
"https://js.cx/images-load/3.jpg"
];
for (var i=0; i<sources.length; i++) {
sources[i] += '?'+Math.random();
}
function testLoaded() {
var widthSum = 0;
for (var i = 0; i < sources.length; i++) {
var img = document.createElement('img');
img.src = sources[i];
widthSum += img.width;
function testLoaded() {
var widthSum = 0;
for (var i = 0; i < sources.length; i++) {
var img = document.createElement('img');
img.src = sources[i];
widthSum += img.width;
}
alert(widthSum); // 300!
}
alert(widthSum); // 300!
}
// до загрузки - 0
testLoaded();
// после загрузки - 300
preloadImages(sources, testLoaded);
</script>
// до загрузки - 0
testLoaded();
// после загрузки - 300
preloadImages(sources, testLoaded);
</script>
</body>
</html>
</html>

View file

@ -1,49 +1,50 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function preloadImages(sources, callback) {
/* ваш код */
}
// ---------- Проверка ----------
/* файлы для загрузки */
var sources = [
"https://js.cx/images-load/1.jpg",
"https://js.cx/images-load/2.jpg",
"https://js.cx/images-load/3.jpg"
];
for (var i=0; i<sources.length; i++) {
sources[i] += '?'+Math.random(); // добавляем параметр, чтобы без кеша (для теста)
}
/** если картинка загружена, то можно будет сразу получить её ширину
* создадим все картинки и проверим, есть ли у них ширина
*/
function testLoaded() {
var widthSum = 0;
for (var i = 0; i < sources.length; i++) {
var img = document.createElement('img');
img.src = sources[i];
widthSum += img.width;
<script>
function preloadImages(sources, callback) {
/* ваш код */
}
// каждое изображение 100x100, общая ширина должна быть 300px
alert(widthSum);
}
// до загрузки - выведет 0
testLoaded();
// ---------- Проверка ----------
// после загрузки - выведет 300
preloadImages(sources, testLoaded);
/* файлы для загрузки */
var sources = [
"https://js.cx/images-load/1.jpg",
"https://js.cx/images-load/2.jpg",
"https://js.cx/images-load/3.jpg"
];
for (var i = 0; i < sources.length; i++) {
sources[i] += '?' + Math.random(); // добавляем параметр, чтобы без кеша (для теста)
}
</script>
/** если картинка загружена, то можно будет сразу получить её ширину
* создадим все картинки и проверим, есть ли у них ширина
*/
function testLoaded() {
var widthSum = 0;
for (var i = 0; i < sources.length; i++) {
var img = document.createElement('img');
img.src = sources[i];
widthSum += img.width;
}
// каждое изображение 100x100, общая ширина должна быть 300px
alert(widthSum);
}
// до загрузки - выведет 0
testLoaded();
// после загрузки - выведет 300
preloadImages(sources, testLoaded);
</script>
</body>
</html>
</html>

View file

@ -1,41 +1,42 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
<script>
function addScript(src, callback) {
var script = document.createElement('script');
script.src = src;
var s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore(script, s);
function addScript(src, callback) {
var script = document.createElement('script');
script.src = src;
var s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore(script, s);
var loaded = false;
var loaded = false;
function onload() {
if (loaded) return; // повторный вызов
loaded = true;
callback();
}
script.onload = onload; // все браузеры, IE с версии 9
script.onreadystatechange = function() { // IE8-
if (this.readyState == 'loaded' || this.readyState == 'complete') {
setTimeout(onload, 0);
}
};
function onload() {
if (loaded) return; // повторный вызов
loaded = true;
callback();
}
script.onload = onload; // все браузеры, IE с версии 9
script.onreadystatechange = function () { // IE8-
if (this.readyState == 'loaded' || this.readyState == 'complete') {
setTimeout(onload, 0);
}
};
}
addScript("go.js", function() {
go();
});
</script>
addScript("go.js", function() {
go();
});
</script>
</body>
</html>
</html>

View file

@ -1,21 +1,22 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
<script>
function addScript(src, callback) {
/* ваш код */
}
function addScript(src, callback) {
/* ваш код */
}
addScript("go.js", function() {
go();
});
</script>
addScript("go.js", function() {
go();
});
</script>
</body>
</html>
</html>

View file

@ -1,51 +1,54 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function addScript(src) {
var script = document.createElement('script');
script.src = src;
var s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore(script, s);
return script;
}
function addScripts(scripts, callback) {
var loaded = {}; // Для загруженных файлов loaded[i] = true
var counter = 0;
function onload(i) {
if (loaded[i]) return; // лишний вызов onload/onreadystatechange
loaded[i] = true;
counter++;
if (counter == scripts.length) callback();
<script>
function addScript(src) {
var script = document.createElement('script');
script.src = src;
var s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore(script, s);
return script;
}
for (var i = 0; i < scripts.length; i++) (function(i) {
var script = addScript(scripts[i]);
function addScripts(scripts, callback) {
var loaded = {}; // Для загруженных файлов loaded[i] = true
var counter = 0;
script.onload = function() {
onload(i);
};
function onload(i) {
if (loaded[i]) return; // лишний вызов onload/onreadystatechange
loaded[i] = true;
counter++;
if (counter == scripts.length) callback();
}
script.onreadystatechange = function() { // IE8-
if (this.readyState == 'loaded' || this.readyState == 'complete') {
setTimeout(this.onload, 0); // возможны повторные вызовы onload
}
};
for (var i = 0; i < scripts.length; i++)(function(i) {
var script = addScript(scripts[i]);
}(i));
script.onload = function() {
onload(i);
};
}
script.onreadystatechange = function() { // IE8-
if (this.readyState == 'loaded' || this.readyState == 'complete') {
setTimeout(this.onload, 0); // возможны повторные вызовы onload
}
};
addScripts(["a.js", "b.js", "c.js"], function() { a() });
}(i));
</script>
}
addScripts(["a.js", "b.js", "c.js"], function() {
a()
});
</script>
</body>
</html>
</html>

View file

@ -1,18 +1,21 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
<script>
/* ваш код */
/* ваш код */
// функция a() сработает только если загружены a.js, b.js, c.js
addScripts(["a.js", "b.js", "c.js"], function() { a() });
</script>
// функция a() сработает только если загружены a.js, b.js, c.js
addScripts(["a.js", "b.js", "c.js"], function() {
a()
});
</script>
</body>
</html>
</html>

View file

@ -1,167 +1,175 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
height: 2000px; /* подсказка должна работать независимо от прокрутки */
}
.tooltip {
position: fixed;
z-index:100; /* подсказка должна перекрывать другие элементы */
padding: 10px 20px;
/* красивости... */
border: 1px solid #b3c9ce;
border-radius: 4px;
text-align: center;
font: italic 14px/1.3 arial, sans-serif;
color: #333;
background: #fff;
box-shadow: 3px 3px 3px rgba(0,0,0,.3);
}
#house {
margin-top: 50px;
width: 400px;
border: 1px solid brown;
}
#roof {
width: 0;
height: 0;
border-left: 200px solid transparent;
border-right: 200px solid transparent;
<meta charset="utf-8">
<style>
body {
height: 2000px;
/* подсказка должна работать независимо от прокрутки */
}
border-bottom: 20px solid brown;
margin-top: -20px;
}
p {
text-align: justify;
margin: 10px 3px;
}
</style>
.tooltip {
position: fixed;
z-index: 100;
/* подсказка должна перекрывать другие элементы */
padding: 10px 20px;
/* красивости... */
border: 1px solid #b3c9ce;
border-radius: 4px;
text-align: center;
font: italic 14px/1.3 arial, sans-serif;
color: #333;
background: #fff;
box-shadow: 3px 3px 3px rgba(0, 0, 0, .3);
}
#house {
margin-top: 50px;
width: 400px;
border: 1px solid brown;
}
#roof {
width: 0;
height: 0;
border-left: 200px solid transparent;
border-right: 200px solid transparent;
border-bottom: 20px solid brown;
margin-top: -20px;
}
p {
text-align: justify;
margin: 10px 3px;
}
</style>
</head>
<body>
<div data-tooltip="Это внутренность дома" id="house">
<div data-tooltip="Это крыша" id="roof"></div>
<div data-tooltip="Это внутренность дома" id="house">
<div data-tooltip="Это крыша" id="roof"></div>
<p>Жили-были на свете три поросёнка. Три брата.</p>
<p>Жили-были на свете три поросёнка. Три брата.</p>
<p>Все одинакового роста, кругленькие, розовые, с одинаковыми весёлыми хвостиками.</p>
<p>Все одинакового роста, кругленькие, розовые, с одинаковыми весёлыми хвостиками.</p>
<p>Даже имена у них были похожи. Звали поросят Ниф-Ниф, Нуф-Нуф и Наф-Наф. Всё лето они кувыркались в зелёной траве, грелись на солнышке, нежились в лужах.</p>
<p>Даже имена у них были похожи. Звали поросят Ниф-Ниф, Нуф-Нуф и Наф-Наф. Всё лето они кувыркались в зелёной траве, грелись на солнышке, нежились в лужах.</p>
<p>Но вот наступила осень. <a href="http://ru.wikipedia.org/wiki/Три_поросёнка" data-tooltip="Читать дальше&hellip;">Наведи на меня</a></p>
<p>Но вот наступила осень. <a href="http://ru.wikipedia.org/wiki/Три_поросёнка" data-tooltip="Читать дальше&hellip;">Наведи на меня</a></p>
</div>
</div>
<script>
<script>
var showingTooltip;
var showingTooltip;
document.onmouseover = function(e) {
var target = e.target;
document.onmouseover = function(e) {
var target = e.target;
// ВАЖНО: mouseover может сработать сразу на потомке
// минуя родителя (при быстром движении мышью)
// ВАЖНО: mouseover может сработать сразу на потомке
// минуя родителя (при быстром движении мышью)
// пройти вверх до первого элемента с data-tooltip
while (target !== this) {
var tooltip = target.getAttribute('data-tooltip');
if (tooltip) break;
target = target.parentNode;
}
// пройти вверх до первого элемента с data-tooltip
while (target !== this) {
var tooltip = target.getAttribute('data-tooltip');
if (tooltip) break;
target = target.parentNode;
}
if (!tooltip) return;
if (!tooltip) return;
// показать и запомнить подсказку
showingTooltip = showTooltip(tooltip, target);
}
document.onmouseout = function() {
// возможно такое, что mouseout сработал, а мы все еще внутри элемента (всплытие)
// но в этом случае сразу же будет и mouseover,
// то есть подсказка будет уничтожена и тут же показана заново
//
// это лишние расходы, их можно избежать дополнительными проверками
if (showingTooltip) {
document.body.removeChild(showingTooltip);
showingTooltip = false;
}
}
function showTooltip(text, elem) {
var tooltipElem = document.createElement('div');
tooltipElem.className = 'tooltip';
tooltipElem.innerHTML = text;
document.body.appendChild(tooltipElem);
var coords = elem.getBoundingClientRect();
var left = coords.left + (elem.offsetWidth - tooltipElem.offsetWidth)/2;
if (left < 0) left = 0; // не вылезать за левую границу экрана
// не вылезать за верхнюю границу окна
var top = coords.top - tooltipElem.offsetHeight - 5;
if (top < 0) {
top = coords.top + elem.offsetHeight + 5;
}
tooltipElem.style.left = left + 'px';
tooltipElem.style.top = top + 'px';
return tooltipElem;
}
function getCoords(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
function getPageScroll() {
if (window.pageXOffset != undefined) {
return {
left: pageXOffset,
top: pageYOffset
// показать и запомнить подсказку
showingTooltip = showTooltip(tooltip, target);
}
}
var html = document.documentElement;
var body = document.body;
document.onmouseout = function() {
// возможно такое, что mouseout сработал, а мы все еще внутри элемента (всплытие)
// но в этом случае сразу же будет и mouseover,
// то есть подсказка будет уничтожена и тут же показана заново
//
// это лишние расходы, их можно избежать дополнительными проверками
if (showingTooltip) {
document.body.removeChild(showingTooltip);
showingTooltip = false;
}
var top = html.scrollTop || body && body.scrollTop || 0;
top -= html.clientTop;
}
var left = html.scrollLeft || body && body.scrollLeft || 0;
left -= html.clientLeft;
return { top: top, left: left };
}
function showTooltip(text, elem) {
var tooltipElem = document.createElement('div');
tooltipElem.className = 'tooltip';
tooltipElem.innerHTML = text;
document.body.appendChild(tooltipElem);
</script>
var coords = elem.getBoundingClientRect();
var left = coords.left + (elem.offsetWidth - tooltipElem.offsetWidth) / 2;
if (left < 0) left = 0; // не вылезать за левую границу экрана
// не вылезать за верхнюю границу окна
var top = coords.top - tooltipElem.offsetHeight - 5;
if (top < 0) {
top = coords.top + elem.offsetHeight + 5;
}
tooltipElem.style.left = left + 'px';
tooltipElem.style.top = top + 'px';
return tooltipElem;
}
function getCoords(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return {
top: Math.round(top),
left: Math.round(left)
};
}
function getPageScroll() {
if (window.pageXOffset != undefined) {
return {
left: pageXOffset,
top: pageYOffset
}
}
var html = document.documentElement;
var body = document.body;
var top = html.scrollTop || body && body.scrollTop || 0;
top -= html.clientTop;
var left = html.scrollLeft || body && body.scrollLeft || 0;
left -= html.clientLeft;
return {
top: top,
left: left
};
}
</script>
</body>
</html>
</html>

View file

@ -1,50 +1,52 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
height: 2000px; /* подсказка должна работать при прокрутке */
}
#house {
margin-top: 50px;
width: 400px;
border: 1px solid brown;
}
#roof {
width: 0;
height: 0;
border-left: 200px solid transparent;
border-right: 200px solid transparent;
<meta charset="utf-8">
<style>
body {
height: 2000px;
/* подсказка должна работать при прокрутке */
}
border-bottom: 20px solid brown;
margin-top: -20px;
}
p {
text-align: justify;
margin: 10px 3px;
}
</style>
#house {
margin-top: 50px;
width: 400px;
border: 1px solid brown;
}
#roof {
width: 0;
height: 0;
border-left: 200px solid transparent;
border-right: 200px solid transparent;
border-bottom: 20px solid brown;
margin-top: -20px;
}
p {
text-align: justify;
margin: 10px 3px;
}
</style>
</head>
<body>
<div data-tooltip="Это внутренность дома" id="house">
<div data-tooltip="Это крыша" id="roof"></div>
<div data-tooltip="Это внутренность дома" id="house">
<div data-tooltip="Это крыша" id="roof"></div>
<p>Жили-были на свете три поросёнка. Три брата.</p>
<p>Жили-были на свете три поросёнка. Три брата.</p>
<p>Все одинакового роста, кругленькие, розовые, с одинаковыми весёлыми хвостиками.</p>
<p>Все одинакового роста, кругленькие, розовые, с одинаковыми весёлыми хвостиками.</p>
<p>Даже имена у них были похожи. Звали поросят Ниф-Ниф, Нуф-Нуф и Наф-Наф. Всё лето они кувыркались в зелёной траве, грелись на солнышке, нежились в лужах.</p>
<p>Даже имена у них были похожи. Звали поросят Ниф-Ниф, Нуф-Нуф и Наф-Наф. Всё лето они кувыркались в зелёной траве, грелись на солнышке, нежились в лужах.</p>
<p>Но вот наступила осень. <a href="http://ru.wikipedia.org/wiki/Три_поросёнка" data-tooltip="Читать дальше&hellip;">Наведи на меня</a></p>
<p>Но вот наступила осень. <a href="http://ru.wikipedia.org/wiki/Три_поросёнка" data-tooltip="Читать дальше&hellip;">Наведи на меня</a></p>
</div>
</div>
</body>
</html>
</html>

View file

@ -1,44 +1,43 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="hoverIntent.js"></script>
</head>
<body>
<div id="elem" class="clock">
<span class="hours">12</span>
:
<span class="minutes">30</span>
:
<span class="hours">12</span> :
<span class="minutes">30</span> :
<span class="seconds">00</span>
</div>
<script>
var tooltip = document.createElement('div');
tooltip.className = "tooltip";
tooltip.innerHTML = "Подсказка";
var tooltip = document.createElement('div');
tooltip.className = "tooltip";
tooltip.innerHTML = "Подсказка";
new HoverIntent({
elem: elem,
over: function() {
tooltip.style.left = this.getBoundingClientRect().left + 'px';
tooltip.style.top = this.getBoundingClientRect().bottom + 5 + 'px';
document.body.appendChild(tooltip);
},
out: function() {
document.body.removeChild(tooltip);
}
});
new HoverIntent({
elem: elem,
over: function() {
tooltip.style.left = this.getBoundingClientRect().left + 'px';
tooltip.style.top = this.getBoundingClientRect().bottom + 5 + 'px';
document.body.appendChild(tooltip);
},
out: function() {
document.body.removeChild(tooltip);
}
});
</script>
</body>
</html>

View file

@ -1,44 +1,43 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="hoverIntent.js"></script>
</head>
<body>
<div id="elem" class="clock">
<span class="hours">12</span>
:
<span class="minutes">30</span>
:
<span class="hours">12</span> :
<span class="minutes">30</span> :
<span class="seconds">00</span>
</div>
<script>
var tooltip = document.createElement('div');
tooltip.className = "tooltip";
tooltip.innerHTML = "Подсказка";
var tooltip = document.createElement('div');
tooltip.className = "tooltip";
tooltip.innerHTML = "Подсказка";
new HoverIntent({
elem: elem,
over: function() {
tooltip.style.left = this.getBoundingClientRect().left + 'px';
tooltip.style.top = this.getBoundingClientRect().bottom + 5 + 'px';
document.body.appendChild(tooltip);
},
out: function() {
document.body.removeChild(tooltip);
}
});
new HoverIntent({
elem: elem,
over: function() {
tooltip.style.left = this.getBoundingClientRect().left + 'px';
tooltip.style.top = this.getBoundingClientRect().bottom + 5 + 'px';
document.body.appendChild(tooltip);
},
out: function() {
document.body.removeChild(tooltip);
}
});
</script>
</body>
</html>

View file

@ -1,49 +1,79 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table id="table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong><br>Metal<br>Silver<br>Elders
</td>
<td class="n"><strong>North</strong><br>Water<br>Blue<br>Change
</td>
<td class="ne"><strong>Northeast</strong><br>Earth<br>Yellow<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong><br>Metal<br>Gold<br>Youth
</td>
<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>
<textarea id="text"></textarea>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<input type="button" onclick="text.value=''" value="Очистить">
<body>
<table id="table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong>
<br>Metal
<br>Silver
<br>Elders
</td>
<td class="n"><strong>North</strong>
<br>Water
<br>Blue
<br>Change
</td>
<td class="ne"><strong>Northeast</strong>
<br>Earth
<br>Yellow
<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong>
<br>Metal
<br>Gold
<br>Youth
</td>
<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>
<textarea id="text"></textarea>
<input type="button" onclick="text.value=''" value="Очистить">
<script src="script.js"></script>
</body>
<script src="script.js"></script>
</body>
</html>

View file

@ -1,49 +1,79 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table id="table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong><br>Metal<br>Silver<br>Elders
</td>
<td class="n"><strong>North</strong><br>Water<br>Blue<br>Change
</td>
<td class="ne"><strong>Northeast</strong><br>Earth<br>Yellow<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong><br>Metal<br>Gold<br>Youth
</td>
<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>
<textarea id="text"></textarea>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<input type="button" onclick="text.value=''" value="Очистить">
<body>
<table id="table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong>
<br>Metal
<br>Silver
<br>Elders
</td>
<td class="n"><strong>North</strong>
<br>Water
<br>Blue
<br>Change
</td>
<td class="ne"><strong>Northeast</strong>
<br>Earth
<br>Yellow
<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong>
<br>Metal
<br>Gold
<br>Youth
</td>
<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>
<textarea id="text"></textarea>
<input type="button" onclick="text.value=''" value="Очистить">
<script src="script.js"></script>
</body>
<script src="script.js"></script>
</body>
</html>

View file

@ -1,49 +1,79 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table id="table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong><br>Metal<br>Silver<br>Elders
</td>
<td class="n"><strong>North</strong><br>Water<br>Blue<br>Change
</td>
<td class="ne"><strong>Northeast</strong><br>Earth<br>Yellow<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong><br>Metal<br>Gold<br>Youth
</td>
<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>
<textarea id="text"></textarea>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<input type="button" onclick="text.value=''" value="Очистить">
<body>
<table id="table">
<tr>
<th colspan="3"><em>Bagua</em> Chart: Direction, Element, Color, Meaning</th>
</tr>
<tr>
<td class="nw"><strong>Northwest</strong>
<br>Metal
<br>Silver
<br>Elders
</td>
<td class="n"><strong>North</strong>
<br>Water
<br>Blue
<br>Change
</td>
<td class="ne"><strong>Northeast</strong>
<br>Earth
<br>Yellow
<br>Direction
</td>
</tr>
<tr>
<td class="w"><strong>West</strong>
<br>Metal
<br>Gold
<br>Youth
</td>
<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>
<textarea id="text"></textarea>
<input type="button" onclick="text.value=''" value="Очистить">
<script src="script.js"></script>
</body>
<script src="script.js"></script>
</body>
</html>

View file

@ -1,19 +1,22 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="blue" onmouseenter="log(event)" onmouseleave="log(event)">
<div id="red"></div>
</div>
<textarea id="text"></textarea>
<input type="button" onclick="text.value=''" value="Очистить">
<script src="script.js"></script>
</body>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="blue" onmouseenter="log(event)" onmouseleave="log(event)">
<div id="red"></div>
</div>
<textarea id="text"></textarea>
<input type="button" onclick="text.value=''" value="Очистить">
<script src="script.js"></script>
</body>
</html>

View file

@ -1,22 +1,23 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="blue" onmouseover="mouselog(event)" onmouseout="mouselog(event)">
<div class="blue" onmouseover="mouselog(event)" onmouseout="mouselog(event)">
<div class="red"></div>
</div>
</div>
<textarea id="text">mouseover [target: blue]
mouseout [target: blue]
mouseover [target: red]
</textarea>
<input type="button" onclick="text.value=''" value="Очистить">
<textarea id="text">mouseover [target: blue] mouseout [target: blue] mouseover [target: red]
</textarea>
<input type="button" onclick="text.value=''" value="Очистить">
<script src="script.js"></script>
<script src="script.js"></script>
</body>
</html>

View file

@ -1,20 +1,23 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="green">
<div id="red">Тест</div>
</div>
<input onclick="clearText()" value="Очистить" type="button">
<input onclick="clearText()" value="Очистить" type="button">
<textarea id="text"></textarea>
<script src="script.js"></script>
</body>
</html>

View file

@ -1,34 +1,37 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="smiley-green">
<div class="left-eye"></div>
<div class="right-eye"></div>
<div class="smile"></div>
<div class="left-eye"></div>
<div class="right-eye"></div>
<div class="smile"></div>
</div>
<div class="smiley-yellow">
<div class="left-eye"></div>
<div class="right-eye"></div>
<div class="smile"></div>
<div class="left-eye"></div>
<div class="right-eye"></div>
<div class="smile"></div>
</div>
<div class="smiley-red">
<div class="left-eye"></div>
<div class="right-eye"></div>
<div class="smile"></div>
<div class="left-eye"></div>
<div class="right-eye"></div>
<div class="smile"></div>
</div>
<textarea id="log" style="width:400px;height:100px">Здесь будут события и relatedTarget
</textarea>
</textarea>
<script src="script.js"></script>
</body>
</html>
</html>

View file

@ -1,65 +1,66 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="slider" class="slider">
<div class="thumb"></div>
</div>
<div id="slider" class="slider">
<div class="thumb"></div>
</div>
<script>
<script>
var sliderElem = document.getElementById('slider');
var thumbElem = sliderElem.children[0];
var sliderElem = document.getElementById('slider');
var thumbElem = sliderElem.children[0];
thumbElem.onmousedown = function(e) {
var thumbCoords = getCoords(thumbElem);
var shiftX = e.pageX - thumbCoords.left;
// shiftY здесь не нужен, слайдер двигается только по горизонтали
thumbElem.onmousedown = function(e) {
var thumbCoords = getCoords(thumbElem);
var shiftX = e.pageX - thumbCoords.left;
// shiftY здесь не нужен, слайдер двигается только по горизонтали
var sliderCoords = getCoords(sliderElem);
var sliderCoords = getCoords(sliderElem);
document.onmousemove = function(e) {
// вычесть координату родителя, т.к. position: relative
var newLeft = e.pageX - shiftX - sliderCoords.left;
document.onmousemove = function(e) {
// вычесть координату родителя, т.к. position: relative
var newLeft = e.pageX - shiftX - sliderCoords.left;
// курсор ушёл вне слайдера
if (newLeft < 0) {
newLeft = 0;
}
var rightEdge = sliderElem.offsetWidth - thumbElem.offsetWidth;
if (newLeft > rightEdge) {
newLeft = rightEdge;
}
thumbElem.style.left = newLeft + 'px';
}
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
};
return false; // disable selection start (cursor change)
};
thumbElem.ondragstart = function() {
return false;
};
function getCoords(elem) { // кроме IE8-
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
// курсор ушёл вне слайдера
if (newLeft < 0) {
newLeft = 0;
}
var rightEdge = sliderElem.offsetWidth - thumbElem.offsetWidth;
if (newLeft > rightEdge) {
newLeft = rightEdge;
}
thumbElem.style.left = newLeft + 'px';
}
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
};
return false; // disable selection start (cursor change)
};
thumbElem.ondragstart = function() {
return false;
};
function getCoords(elem) { // кроме IE8-
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}
</script>
</script>
</body>
</html>

View file

@ -1,18 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="slider" class="slider">
<div class="thumb"></div>
</div>
<div id="slider" class="slider">
<div class="thumb"></div>
</div>
<script>
// ...Ваш код..
</script>
<script>
// ...Ваш код..
</script>
</body>
</html>

View file

@ -1,21 +1,23 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="soccer.css">
</head>
<body>
<h2>Расставьте супергероев по полю.</h2>
<p>Супергерои и мяч -- это элементы с классом "draggable". Сделайте так, чтобы их можно было переносить.</p>
<p>Важно: если супергероя подносят к низу или верху страницы, она должна автоматически прокручиваться. Если страница помещается на вашем экране целиком и не имеет вертикальной прокрутки -- сделайте окно браузера меньше, чтобы протестировать эту возможность.</p>
<p>Да, и ещё: супергерои ни при каких условиях не должны попасть за край экрана.</p>
<div id="field">
</div>
<div class="hero draggable" id="hero1"></div>
@ -31,4 +33,5 @@
<script src="soccer.js"></script>
</body>
</html>
</html>

View file

@ -1,21 +1,23 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="soccer.css">
</head>
<body>
<h2>Расставьте супергероев по полю.</h2>
<p>Супергерои и мяч -- это элементы с классом "draggable". Сделайте так, чтобы их можно было переносить.</p>
<p>Важно: если супергероя подносят к низу или верху страницы, она должна автоматически прокручиваться. Если страница помещается на вашем экране целиком и не имеет вертикальной прокрутки -- сделайте окно браузера меньше, чтобы протестировать эту возможность.</p>
<p>Да, и ещё: супергерои ни при каких условиях не должны попасть за край экрана.</p>
<div id="field">
</div>
<div class="hero draggable" id="hero1"></div>
@ -31,4 +33,5 @@
<script src="soccer.js"></script>
</body>
</html>
</html>

View file

@ -1,44 +1,46 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="height: 200px">
<p>Кликните по мячу и тяните, чтобы двигать его.</p>
<p>Кликните по мячу и тяните, чтобы двигать его.</p>
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
<script>
var ball = document.getElementById('ball');
<script>
var ball = document.getElementById('ball');
ball.onmousedown = function(e) {
ball.onmousedown = function(e) {
ball.style.position = 'absolute';
moveAt(e);
ball.style.position = 'absolute';
moveAt(e);
document.body.appendChild(ball);
document.body.appendChild(ball);
ball.style.zIndex = 1000; // показывать мяч над другими элементами
function moveAt(e) {
ball.style.left = e.pageX - ball.offsetWidth/2 + 'px';
ball.style.top = e.pageY - ball.offsetHeight/2 + 'px';
}
ball.style.zIndex = 1000; // показывать мяч над другими элементами
document.onmousemove = function(e) {
moveAt(e);
};
function moveAt(e) {
ball.style.left = e.pageX - ball.offsetWidth / 2 + 'px';
ball.style.top = e.pageY - ball.offsetHeight / 2 + 'px';
}
document.onmousemove = function(e) {
moveAt(e);
};
ball.onmouseup = function() {
document.onmousemove = null;
ball.onmouseup = null;
};
}
</script>
ball.onmouseup = function() {
document.onmousemove = null;
ball.onmouseup = null;
};
}
</script>
</body>
</html>

View file

@ -1,49 +1,51 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="height: 200px">
<p>Кликните по мячу и тяните, чтобы двигать его.</p>
<p>Кликните по мячу и тяните, чтобы двигать его.</p>
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
<script>
var ball = document.getElementById('ball');
<script>
var ball = document.getElementById('ball');
ball.onmousedown = function(e) {
ball.onmousedown = function(e) {
ball.style.position = 'absolute';
moveAt(e);
ball.style.position = 'absolute';
moveAt(e);
document.body.appendChild(ball);
document.body.appendChild(ball);
ball.style.zIndex = 1000; // показывать мяч над другими элементами
function moveAt(e) {
ball.style.left = e.pageX - ball.offsetWidth/2 + 'px';
ball.style.top = e.pageY - ball.offsetHeight/2 + 'px';
}
ball.style.zIndex = 1000; // показывать мяч над другими элементами
document.onmousemove = function(e) {
moveAt(e);
};
function moveAt(e) {
ball.style.left = e.pageX - ball.offsetWidth / 2 + 'px';
ball.style.top = e.pageY - ball.offsetHeight / 2 + 'px';
}
ball.onmouseup = function() {
document.onmousemove = null;
ball.onmouseup = null;
};
}
document.onmousemove = function(e) {
moveAt(e);
};
ball.onmouseup = function() {
document.onmousemove = null;
ball.onmouseup = null;
};
}
ball.ondragstart = function() {
return false;
};
ball.ondragstart = function() {
return false;
};
</script>
</script>
</body>
</html>

View file

@ -1,63 +1,65 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="height: 200px">
<p>Кликните по мячу и тяните, чтобы двигать его.</p>
<p>Кликните по мячу и тяните, чтобы двигать его.</p>
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
<img src="https://js.cx/clipart/ball.svg" style="cursor:pointer" width="40" height="40" id="ball">
<script>
var ball = document.getElementById('ball');
<script>
var ball = document.getElementById('ball');
ball.onmousedown = function(e) {
ball.onmousedown = function(e) {
var coords = getCoords(ball);
var shiftX = e.pageX - coords.left;
var shiftY = e.pageY - coords.top;
var coords = getCoords(ball);
var shiftX = e.pageX - coords.left;
var shiftY = e.pageY - coords.top;
ball.style.position = 'absolute';
document.body.appendChild(ball);
moveAt(e);
ball.style.position = 'absolute';
document.body.appendChild(ball);
moveAt(e);
ball.style.zIndex = 1000; // над другими элементами
ball.style.zIndex = 1000; // над другими элементами
function moveAt(e) {
ball.style.left = e.pageX - shiftX + 'px';
ball.style.top = e.pageY - shiftY + 'px';
}
function moveAt(e) {
ball.style.left = e.pageX - shiftX + 'px';
ball.style.top = e.pageY - shiftY + 'px';
}
document.onmousemove = function(e) {
moveAt(e);
};
document.onmousemove = function(e) {
moveAt(e);
};
ball.onmouseup = function() {
document.onmousemove = null;
ball.onmouseup = null;
};
ball.onmouseup = function() {
document.onmousemove = null;
ball.onmouseup = null;
};
}
}
ball.ondragstart = function() {
return false;
};
ball.ondragstart = function() {
return false;
};
function getCoords(elem) { // кроме IE8-
var box = elem.getBoundingClientRect();
function getCoords(elem) { // кроме IE8-
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}
</script>
}
</script>
</body>
</html>

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