So basically if you get what I am doing, I want it to be such that when I click the next button the color of one goes to three and three goes to two and two goes to one. I have been trying to make it fetch the color of two but without success
<!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>
CodePudding user response:
A style that is inherited from a class is not accessible via an individual style property. You can however use getComputedStyle
, although I would actually just store those colors in variables. But for the purpose of showing what getComputedStyle
can do, here is an adapted script:
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" ></div>
<div id="two" ></div>
<div id="three" ></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)">
CodePudding user response:
You can use the window.getComputedStyle() to acces all the CSS properties of an element. Here you can use the
window.getComputedStyle(document.getElementById("two")).backgroundColor;
to access the background color of your second div element.
Further documentation on getComputedStyle() can be accesed here:
<!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>