Entonces, básicamente, si entiendes lo que estoy haciendo, quiero que sea tal que cuando haga clic en el siguiente botón, el color de uno pase a tres, el tres pase a dos y el dos pase a uno. He estado tratando de hacer que obtenga el color de dos pero sin éxito.
<!DOCTYPE html> <html> <Head> <style> div { height: 50px; } #one { width: 100%; background-color: #f00; } #two { width: 50%; background-color: #0f0; float: left; } #three { width: 50%; background-color: #00f; float: right; } </style> <script> function oneToTwo() { document.getElementById("one").style.backgroundColor = document.getElementById("two").style.backgroundColor; } </script> </Head> <body> <div id="one"></div> <div id="two"></div> <div id="three"></div> <input type="button" value="Back" title="The back button"> <input type="button" value="Next" title="The next button" onclick="oneToTwo()"> </body> </html>No se puede acceder a un estilo que se hereda de una clase a través de una propiedad de estilo individual. Sin embargo, puede usar getComputedStyle , aunque en realidad solo almacenaría esos colores en variables. Pero con el propósito de mostrar lo que puede hacer getComputedStyle , aquí hay un script adaptado:
let areas = document.querySelectorAll(".area"); function rotate(dir=1) { // Fetch colors let colors = Array.from(areas, area => getComputedStyle(area).backgroundColor); // Rotate them if (dir == 1) colors.push(colors.shift()); else colors.unshift(colors.pop()); // Assign them back areas.forEach(area => area.style.backgroundColor = colors.shift()); } div { height: 50px; } #one { width: 100%; background-color: #f00; } #two { width: 50%; background-color: #0f0; float: left; } #three { width: 50%; background-color: #00f; float: right; } <div id="one" class="area"></div> <div id="two" class="area"></div> <div id="three" class="area"></div> <input type="button" value="Back" title="The back button" onclick="rotate(-1)"> <input type="button" value="Next" title="The next button" onclick="rotate(1)">Puede usar window.getComputedStyle() para acceder a todas las propiedades CSS de un elemento. Aquí puedes usar el
window.getComputedStyle(document.getElementById("two")).backgroundColor;para acceder al color de fondo de su segundo elemento div.
Se puede acceder a más documentación sobre getComputedStyle() aquí:
<!DOCTYPE html> <html> <Head> <style> div { height: 50px; } #one { width: 100%; background-color: #f00; } #two { width: 50%; background-color: #0f0; float: left; } #three { width: 50%; background-color: #00f; float: right; } </style> <script> function oneToTwo() { document.getElementById("one").style.backgroundColor = window.getComputedStyle(document.getElementById("two")).backgroundColor; } </script> </Head> <body> <div id="one"></div> <div id="two"></div> <div id="three"></div> <input type="button" value="Back" title="The back button"> <input type="button" value="Next" title="The next button" onclick="oneToTwo()"> </body> </html>