En esta práctica de JavaScript he puesto en práctica el uso del Array en este lenguaje de programación.
Cuando se coloca el ratón encima de las cajas se muestra el nombre del color de dicha caja.
Para poder comprender el código de esta práctica es muy importante conocer el uso del Array en JavaScript y de los eventos onmouseover y onmouseout. Como ayuda puedes echarle un vistazo a los siguientes enlaces:
Código HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Práctica de JavaScript</title>
<link href="estilos.css" rel="stylesheet" type="text/css" />
<script src="funciones.js" type="text/javascript"></script>
</head>
<body>
<p>El ratón está encima de la caja de color:</p>
<h2 id="encabezado">Ninguno</h2>
<div id="contenedor">
<div id="rojo"></div>
<div id="amarillo"></div>
<div id="verde"></div>
<div id="azul"></div>
</div>
</body>
</html>
Código CSS
* {
text-align: center;
}
#contenedor {
width: 1000px;
margin: 0px auto;
}
#rojo, #amarillo, #verde, #azul {
float: left;
width: 225px;
height: 225px;
border: 1px solid black;
margin: 10px;
}
#rojo {
background-color: red;
}
#amarillo {
background-color: yellow;
}
#verde {
background-color: green;
}
#azul {
background-color: blue;
}
Código JavaScript
window.onload=inicializar;
function inicializar() {
document.getElementById("rojo").addEventListener("mouseover", function(){localizarCaja(1);}, false);
document.getElementById("rojo").addEventListener("mouseout", function(){localizarCaja(0);}, false);
document.getElementById("amarillo").addEventListener("mouseover", function(){localizarCaja(2);}, false);
document.getElementById("amarillo").addEventListener("mouseout", function(){localizarCaja(0);}, false);
document.getElementById("verde").addEventListener("mouseover", function(){localizarCaja(3);}, false);
document.getElementById("verde").addEventListener("mouseout", function(){localizarCaja(0);}, false);
document.getElementById("azul").addEventListener("mouseover", function(){localizarCaja(4);}, false);
document.getElementById("azul").addEventListener("mouseout", function(){localizarCaja(0);}, false);
}
function localizarCaja(color) {
let encabezado = document.getElementById("encabezado");
let colores = ["Ninguno", "Rojo", "Amarillo", "Verde", "Azul"];
encabezado.innerHTML = colores[color];
}
Demostración

Esta obra está bajo una licencia de Creative Commons Reconocimiento-NoComercial-SinObraDerivada 4.0 Internacional.