Como manipular propriedades CSS com JavaScript



Neste tutorial, vamos mostrar como como manipular propriedades CSS usando JavaScript. No exemplo, mostraremos como alterar o estilo de algumas propriedades CSS, como cor, tipo e estilo da fonte, esconder e exibir um elemento HTML entre outros exemplos.

HTML

1. Vamos criar primeiro o conteúdo original do nosso exemplo, onde teremos uma frase inserida em uma <div> HTML. Depois, inserimos os botões que servirão para realizar os eventos de manipulação.

<div id="manipula">Eu sou a frase do exemplo. Serei alterada quando você clicar.</div>
<hr>
<h2>Altere a frase acima clicando nos botões</h2>
<button onclick="mudaCor()">Muda cor da fonte </button>
<input type="button" value="Muda tamanho da fonte" onclick="mudaTamanhoFonte()"/>
<input type="button" value="Muda background" onclick="mudaBackground()"/>
<br><br>
<input type="button" value="Deixa em italico" onclick="mudaItalico()"/>
<input type="button" value="Coloca borda" onclick="colocaBorder()"/>
<input type="button" value="Muda a cor da borda" onclick="corBorder()"/>
<br><br>
<input type="button" value="Exclui borda" onclick="excluiBorder()"/>
<input type="button" value="Esconde a div" onclick="escondeDiv()"/>
<input type="button" value="Reaparece com a div" onclick="reapareceDiv()"/>

CSS

1. Agora, vamos criar um estilo inicial para a nossa <div>.

#manipula {
height:50px;
line-height:50px;
color: yellow;
font-size:10pt;
background-color: red;
margin-bottom:15px; 
}

2. Observe que utilizamos as propriedades CSS para centralizar, definir a a cor e o tamanho da fonte do texto da nossa frase. Também definimos  a cor do fundo e a margem inferior da "div". Observe também que identificamos as propriedades através do seletor id = #minipula.

3. Veja agora como fica os nossos elementos HTML com o estilo definido:

4. Observe que os botões adicionados ainda estão sem efeito. Para isto, precisaremos definir o código JavaScript para as funções: mudaCor(), mudaTamanhoFonte()mudaBackground()mudaItalico(), colocaBorder(), excluiBorder(), escondeDiv() e reapareDiv().

JavaScript

1. Vamos criar o código JavaScript para todas as funções:

function mudaCor() {
document.getElementById("manipula").style.color = "#ffffff";
}
 
function mudaTamanhoFonte() {
document.getElementById("manipula").style.fontSize = "20pt";
}
 
function mudaBackground() {
document.getElementById("manipula").style.backgroundColor = "green";
}
 
function mudaItalico() {
document.getElementById("manipula").style.fontStyle = "italic";
}
 
function escondeDiv() {
document.getElementById("manipula").style.display = "none";
}
 
function reapareceDiv() {
document.getElementById("manipula").style.display = "block";
}

function colocaBorder() {
document.getElementById("manipula").style.border = "2px solid black";
}

function corBorder() {
document.getElementById("manipula").style.border = "2px solid #0000ff";
}

function excluiBorder() {
document.getElementById("manipula").style.border = "0px";
}

 2. Explicando o código:

Em todas as funções JavaScript substituímos o valor do estilo CSS da id "manipula" através do método document.getElementById.

Assim, quando clicamos em um botão -  evento "onclick" - de acordo com a função JavaScript, definimos que a propriedade CSS para a nossa "div" HTML seja substituída pela propriedade "style" correspondente.

Isto acontece porque o objeto documento.getElementById faz com que as propriedades CSS da id "manipula" sejam iguais aos elementos da propriedade "style" para cada função, sobrepondo os valores iniciais e alterando o estilo da div id="manipula" onde está o texto.

3. Existem várias propriedades CSS e que podem ser editadas com JavaScript. Abaixo segue uma tabela com as propriedades CSS e suas respectivas propriedades JavaScript.

Propriedade – CSS Referência – JavaScript (style)
background background
background-attachment backgroundAttachment
background-color backgroundColor
background-image backgroundImage
background-position backgroundPosition
background-repeat backgroundRepeat
border border
border-bottom borderBottom
border-bottom-color borderBottomColor
border-bottom-style borderBottomStyle
border-bottom-width borderBottomWidth
border-color borderColor
border-left borderLeft
border-left-color borderLeftColor
border-left-style borderLeftStyle
border-left-width borderLeftWidth
border-right borderRight
border-right-color borderRightColor
border-right-style borderRightStyle
border-right-width borderRightWidth
border-style borderStyle
border-top borderTop
border-top-color borderTopColor
border-top-style borderTopStyle
border-top-width borderTopWidth
border-width borderWidth
clear clear
clip clip
color color
cursor cursor
display display
filter filter
font font
font-family fontFamily
font-size fontSize
font-variant fontVariant
font-weight fontWeight
height height
left left
letter-spacing letterSpacing
line-height lineHeight
list-style listStyle
list-style-image listStyleImage
list-style-position listStylePosition
list-style-type listStyleType
margin margin
margin-bottom marginBottom
margin-left marginLeft
margin-right marginRight
margin-top marginTop
overflow overflow
padding padding
padding-bottom paddingBottom
padding-left paddingLeft
padding-right paddingRight
padding-top paddingTop
page-break-after pageBreakAfter
page-break-before pageBreakBefore
position position
float styleFloat
text-align textAlign
text-decoration textDecoration
text-decoration: blink textDecorationBlink
text-decoration: line-through textDecorationLineThrough
text-decoration: none textDecorationNone
text-decoration: overline textDecorationOverline
text-decoration: underline textDecorationUnderline
text-indent textIndent
text-transform textTransform
top top
vertical-align verticalAlign
visibility visibility
width width
z-index zInde

   DICA: Utilize esse método JavaScript para manipular quase todas as propriedade CSS existentes.

RESULTADO FINAL

Veja agora o nosso exemplo finalizado.

See the Pen oeOQPm by Angelo Luis Ferreira (@angeloalf) on CodePen.

TENTE VOCÊ MESMO

Veja no nosso editor HTML como foi realizado o método JavaScript. No editor, altere os códigos da forma que você desejar. Depois é só copiar os códigos e colar no seu projeto. Clique no link abaixo para abrir nosso editor de testes. (Não esqueça de clicar no botão "Executar" para visualizar os resultados).

Tente você mesmo »  

CÓDIGO COMPLETO DO EXEMPLO

Para copiar e colar nos seus projetos.

HTML

<div id="manipula">Eu sou a frase do exemplo. Serei alterada quando você clicar.</div>
<hr>
<h2>Altere a frase acima clicando nos botões</h2>
<button onclick="mudaCor()">Muda cor da fonte </button>
<input type="button" value="Muda tamanho da fonte" onclick="mudaTamanhoFonte()"/>
<input type="button" value="Muda background" onclick="mudaBackground()"/>
<br><br>
<input type="button" value="Deixa em italico" onclick="mudaItalico()"/>
<input type="button" value="Coloca borda" onclick="colocaBorder()"/>
<input type="button" value="Muda a cor da borda" onclick="corBorder()"/>
<br><br>
<input type="button" value="Exclui borda" onclick="excluiBorder()"/>
<input type="button" value="Esconde a div" onclick="escondeDiv()"/>
<input type="button" value="Reaparece com a div" onclick="reapareceDiv()"/>

CSS

#manipula {
height:50px;
line-height:50px;
color: yellow;
font-size:10pt;
background-color: red;
margin-bottom:15px; 
}

JavaScript

function mudaCor() {
document.getElementById("manipula").style.color = "#ffffff";
}
 
function mudaTamanhoFonte() {
document.getElementById("manipula").style.fontSize = "20pt";
}
 
function mudaBackground() {
document.getElementById("manipula").style.backgroundColor = "green";
}
 
function mudaItalico() {
document.getElementById("manipula").style.fontStyle = "italic";
}
 
function escondeDiv() {
document.getElementById("manipula").style.display = "none";
}
 
function reapareceDiv() {
document.getElementById("manipula").style.display = "block";
}

function colocaBorder() {
document.getElementById("manipula").style.border = "2px solid black";
}

function corBorder() {
document.getElementById("manipula").style.border = "2px solid #0000ff";
}

function excluiBorder() {
document.getElementById("manipula").style.border = "0px";
}

REFERÊNCIA JAVASCRIPT

1. [document.getElementById()] >> Sintaxe e exemplos

O anúncio abaixo ajuda manter o Portal Visual Dicas

Comentários

×

Infomações do site / SEO