JavaScript - Marx Gomes Van der Linden

Transcrição

JavaScript - Marx Gomes Van der Linden
JavaScript
Eventos e DOM
Ferramentas para Internet
Marx Gomes Van der Linden
Document Object Model
O mecanismo de Document Object Model
(DOM) é a ferramenta que permite a total
integração entre Javascript e o documento HTML
no qual ele está integrado.
Web sites dinâmicos = Aplicações Web
http://marx.vanderlinden.com.br/
2
Document Object Model
O mecanismo de DOM mapeia o documento
HTML como uma árvore composta por nós
(Node).
O nó-raiz que, contém todas as tags, é chamado
document.
http://marx.vanderlinden.com.br/
3
Exemplo
http://marx.vanderlinden.com.br/
4
Exemplo
http://marx.vanderlinden.com.br/
5
Node
Propriedades de um nó (Node):
nodeName → Nome do nó
nodeValue → Valor do nó
nodeType → Tipo do nó (inteiro, constante)
ownerDocument → Pai do nó
firstChild → Primeiro filho
lastChild → Último filho
childNodes → Lista contendo todos os filhos
http://marx.vanderlinden.com.br/
6
Node
Propriedades de um nó (Node):
previousSibling → Irmão anterior
nextSibling → Próximo irmão
attributes → Contém os atributos do nó (para
tags)
Propriedade específica de document:
documentElement → Retorna o nó associado à
tag HTML
http://marx.vanderlinden.com.br/
7
function exibeProps(noh, nome){
var props = [
'nodeName', 'nodeValue', 'nodeType',
'ownerDocument', 'firstChild',
'nextSibling', 'documentElement'
];
}
document.write('<h3>'+nome+'</h3><ul>');
for(var i in props){
document.write(
'<li>' + nome + '.<span class="a">'
+ props[i] + '</span> = ' +
'<span class="b">' + noh[props[i]]
+ '</span</li>'
);
}
document.write('</ul>');
http://marx.vanderlinden.com.br/
8
<html>
<head><title>Teste</title></head>
<style>
.a { color:#003399 }
.b { color:#009933 ; font-weight:bold}
</style>
<body><script>
function exibeProps(noh, nome){ /* ... */ }}
var oHtml = document.documentElement;
var oHead = oHtml.firstChild;
var oBody = oHtml.lastChild;
exibeProps(document, 'document');
exibeProps(oHead , 'oHead');
exibeProps(oBody , 'oBody');
</script></body> http://marx.vanderlinden.com.br/
</html>
9
Saída
http://marx.vanderlinden.com.br/
10
Saída
http://marx.vanderlinden.com.br/
11
Relações entre nós
document.write(
(oHead.parentNode == oHtml) + ', '
);
document.write(
(oBody.parentNode == oHtml) + ', '
);
document.write(
(oBody.previousSibling == oHead) + ', '
);
document.write(
(oHead.nextSibling == oBody) + ', '
);
document.write(
oHead.ownerDocument == document);
http://marx.vanderlinden.com.br/
true, true, true, true, true
12
Tipos de nós
Existem 12 tipos de nós, identificados pelas
constantes:
Node.ELEMENT_NODE (1)
Node.ATTRIBUTE_NODE (2)
Node.TEXT_NODE (3)
Node.CDATA_SECTION_NODE (4)
Node.ENTITY_REFERENCE_NODE (5)
Node.ENTITY_NODE (6)
Node.PROCESSING_INSTRUCTION_NODE (7)
http://marx.vanderlinden.com.br/
13
Tipos de nós
Existem 12 tipos de nós, identificados pelas
constantes:
Node.COMMENT_NODE (8)
Node.DOCUMENT_NODE (9)
Node.DOCUMENT_TYPE_NODE (10)
Node.DOCUMENT_FRAGMENT_NODE (11)
Node.NOTATION_NODE (12)
http://marx.vanderlinden.com.br/
14
childNodes
A propriedade childNodes de cada nó contém
um objeto que funciona como um array.
var oHtml = document.documentElement;
var oHead = oHtml.childNodes[0];
var oBody = oHtml.childNodes[1];
Como caso especial, a tag body pode ser
acessada diretamente de document:
var oBody = document.body;
http://marx.vanderlinden.com.br/
15
Acesso a Elementos Específicos
Para cada nó, o DOM define três métodos que
podem ser usados para encontrar mais facilmente
elementos específicos:
getElementsByTagName()
getElementsByName()
getElementById()
http://marx.vanderlinden.com.br/
16
getElementsByTagName
<html>
<head><title>Teste</title>
<style>(...)</style></head>
<body>
<img src="javascript.jpg">
<img src="goomba.jpg">
<script>
function exibeProps(noh, nome){ ... }
var imgs =
document.getElementsByTagName('img');
exibeProps(imgs[0], 'imgs[0]');
exibeProps(imgs[1], 'imgs[1]');
</script>
http://marx.vanderlinden.com.br/
</body></html>
17
getElementsByTagName
http://marx.vanderlinden.com.br/
18
getElementsByTagName()
Exemplo:
Obter todas as imagens pertencentes ao primeiro
parágrafo da página:
var par = document.getElementsByTagname("p");
var imgs =
par[0].getElementsByTagName("img");
http://marx.vanderlinden.com.br/
19
getElementsByName()
Retorna um array contendo todos os elementos
com a propriedade "name" especificada.
Exemplo:
<img name="js" src="javascript.jpg">
<img name="goomba" src="goomba.jpg">
<script>
var goomba =
document.getElementsByName('goomba')[0];
</script>
http://marx.vanderlinden.com.br/
20
getElementsByName()
Problema no Internet Explorer 6.0
getElementsByName() só verifica as tags
input e img.
http://marx.vanderlinden.com.br/
21
getElementById()
Retorna um único elemento HTML, o qual tem o
atributo id especificado.
Geralmente, é a melhor a maneira de se acessar
um elemento específico.
Exemplo:
<img id="js" src="javascript.jpg">
<img id="goomba" src="goomba.jpg">
<script>
var goomba =
document.getElementById('goomba');
</script>
http://marx.vanderlinden.com.br/
22
Atributos
Os atributos HTML de uma tag são mapeados
como propriedades do elemento DOM:
<html><head><title>Teste</title></head>
<script>
function mudaImg(){
var goomba =
document.getElementById('goomba');
goomba.src = 'spikey.png';
}
</script><body>
<img id="goomba" src="goomba.jpg">
<p style="text-align:center"
onClick="mudaImg()">Mudar
imagem</p>
http://marx.vanderlinden.com.br/
</body></html>
23
Saída
http://marx.vanderlinden.com.br/
24
Saída
http://marx.vanderlinden.com.br/
25
Criando e manipulando nós
Além de alterar as propriedades de nós já
existentes, DOM inclui métodos para adicionar
nós à estrutura do documento.
createElement(nome)
createTextNode()
appendChild()
http://marx.vanderlinden.com.br/
26
createElement()
O método createElement funciona como um
método de fábrica, isto é, cria e retorna um
novo elemento HTML.
Sintaxe:
createElement(nome)
O elemento é criado, mas não é adicionado
ainda à árvore.
http://marx.vanderlinden.com.br/
27
createTextNode()
createTextNode é análogo a
createElement, mas cria um nó de texto;
Sintaxe:
createTextNode(texto)
http://marx.vanderlinden.com.br/
28
appendChild
O método appendChild adiciona um elemento
à arvore, como um filho do elemento que o
chamou.
Sintaxe:
appendChild(obj)
http://marx.vanderlinden.com.br/
29
Exemplo
<html>
<head><title>Teste</title>
<script>
function inicializa(){
var p = document.createElement('p');
var texto = document.createTextNode('Hello,
World!');
p.appendChild(texto);
document.body.appendChild(p);
}
</script>
</head>
<body onLoad="inicializa()"></body>
</html>
http://marx.vanderlinden.com.br/
30
Saída
http://marx.vanderlinden.com.br/
31
Exemplo
<html><head><title>Teste</title><style>
div { border:1px solid black; width: 20em ;
text-align:center; background-color:#D5EAFF }
</style><script>
function inicializa(){
var div = document.createElement('div');
var p = document.createElement('p');
var texto = document.createTextNode('Hello,
World!');
div.appendChild(p);
p.appendChild(texto);
document.body.appendChild(div);
}
</script></head>
http://marx.vanderlinden.com.br/
32
<body onLoad="inicializa()"></body></html>
Saída
http://marx.vanderlinden.com.br/
33
Removendo e Substituindo nós
Objetos DOM também têm métodos para
remover e substituir nós filhos:
Sintaxe:
removeChild(obj)
Remove um nó
replaceChild(novoObj, objAntigo)
Remove um nó e substitui por outro
http://marx.vanderlinden.com.br/
34
Exemplo (1/2)
<html>
<head><title>Teste</title>
<style>
div { border:1px solid black; width: 20em ;
text-align:center; background-color:#D5EAFF }
</style>
</head>
<body onLoad="inicializa()">
<div>
<p id="p1">Primeiro parágrafo</p>
<p id="p2">Segundo parágrafo</p>
<p id="p3">Terceiro parágrafo</p>
</div>
http://marx.vanderlinden.com.br/
35
Exemplo (2/2)
<script>
function inicializa(){
var p = document.createElement('p');
var texto = document.createTextNode('Hello,
World!');
p.appendChild(texto);
var div =
document.getElementsByTagName('div')[0];
var p1 = document.getElementById('p1');
var p3 = document.getElementById('p3');
div.removeChild(p1);
div.replaceChild(p, p3);
}
http://marx.vanderlinden.com.br/
</script></body></html>
36
Saída
http://marx.vanderlinden.com.br/
37
insertBefore()
O método insertBefore insere um elemento antes
de outro, no mesmo nível de hierarquia na
árvore.
Sintaxe:
insertBefore(obj_ref, novo_obj)
http://marx.vanderlinden.com.br/
38
<div>
Exemplo
<p id="p1">Primeiro
parágrafo</p>
<p id="p2">Segundo parágrafo</p>
<p id="p3">Terceiro parágrafo</p>
<button onClick="muda()">Clica!</button>
</div>
function muda(){
var p = document.createElement('p');
var texto = document.createTextNode('Here
comes a new challenger!');
p.appendChild(texto);
var p2 = document.getElementById('p2');
var div =
document.getElementsByTagName('div')[0];
div.insertBefore(p, p2);
http://marx.vanderlinden.com.br/
}
39
Saída, antes
http://marx.vanderlinden.com.br/
40
Saída, depois
http://marx.vanderlinden.com.br/
41
CSS e Javascript
É possível utilizar Javascript para modificar a
classe de um elemento HTML.
Como class é uma palavra reservada (embora
não usada) em Javascript, a propriedade
equivalente se chama className.
http://marx.vanderlinden.com.br/
42
Exemplo
<html><head><title>Teste</title><style>
.c1 { background-color: green; color: white;}
.c2 { background-color: blue; color: black; }
</style></head><body>
<p id="p1" class="c1" onClick="muda()">
The book is on the table.</p>
</body><script>
function muda(){
var p = document.getElementById('p1');
if(p.className == 'c1')
p.className = 'c2'
else
p.className = 'c1';
}
43
</script></html> http://marx.vanderlinden.com.br/
Saída
Clique
http://marx.vanderlinden.com.br/
44
Estilos
Os estilos de um objeto são acessados através
da propriedade style. Cada atributo CSS é
mapeado para uma propriedade equivalente
em style.
Atributo em CSS
Propriedade em Javascript
background-color
color
font-family
font-weight
style.backgroundColor
style.color
style.font
style.fontWeight
http://marx.vanderlinden.com.br/
45
Exemplo
<html><head><title>Teste</title><style>
div { border:1px solid black; width: 20em ;
text-align:center; background-color:#D5EAFF }
</style><script>
function liga(){
document.getElementById('meudiv').
style.backgroundColor = 'red';
}
function desliga(){
document.getElementById('meudiv').
style.backgroundColor = '#D5EAFF';
}
</script><body>
<div id="meudiv" onMouseOver="liga()"
onMouseOut="desliga()">Passe
http://marx.vanderlinden.com.br/ o mouse</div>
46
</body></html>
Saída
http://marx.vanderlinden.com.br/
47
Visibilidade de Elementos
A propriedade CSS display controla como um
elemento é exibido na tela.
Valores:
block → Elemento de bloco
inline → Elemento inline
hidden → Não exibe
É possível explorar essa propriedade em
Javascript para alternar a visibilidade de
elementos.
http://marx.vanderlinden.com.br/
48
Exemplo (1/2)
<html><head><title>Teste</title><style>
div { border:1px solid black; width: 20em ;
text-align:center; background-color:#D5EAFF }
</style><script>
function exibe(){
document.getElementById('bloco').
style.display = 'block';
}
function esconde(){
document.getElementById('bloco').
style.display = 'none';
}
</script>
http://marx.vanderlinden.com.br/
49
Exemplo (2/2)
<body>
<p><a href="#" onClick="exibe()">Exibe</a>,
<a href="#" onClick="esconde()">Esconde</a>
</p>
<div id="bloco" style="display:none">Lorem
ipsum dolor sit amet, consectetuer adipiscing
elit. Morbi dapibus. Quisque vehicula, massa
non lobortis tempus, tortor nisi accumsan
mauris, quis iaculis elit lacus nec lacus.
Morbi ac risus. Sed adipiscing ante at magna.
In tempus nunc sed risus. Donec pretium magna
a dui ultrices viverra.</div>
<p><em>Fim.</em></p>
</body>
http://marx.vanderlinden.com.br/
50
</html>
Saída
http://marx.vanderlinden.com.br/
51

Documentos relacionados

Roteiro 13 - André Moraes [email protected]

Roteiro 13 - André Moraes chameoandre@gmail.com Agrupamentos de Elementos Quando é necessário alterar um elemento em uma página é comum o uso da funcionalidade proposta com o método document.getElementById(“idElemento”).propriedade, porém quando...

Leia mais