所以基本上,如果你明白我在做什么,我希望它是這樣的,當我點擊下一個按鈕時,一的顏色變成三,三的顏色變成二,二的顏色變成一。我一直試圖讓它獲取兩個顏色但沒有成功
<!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>
uj5u.com熱心網友回復:
從類繼承的樣式不能通過單獨的樣式屬性訪問。但是,您可以使用getComputedStyle,盡管我實際上只是將這些顏色存盤在變數中。但是為了展示getComputedStyle可以做什么,這里有一個改編的腳本:
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)">
uj5u.com熱心網友回復:
您可以使用 window.getComputedStyle() 來訪問元素的所有 CSS 屬性。在這里您可以使用
window.getComputedStyle(document.getElementById("two")).backgroundColor;
訪問第二個 div 元素的背景顏色。
可以在此處訪問有關 getComputedStyle() 的更多檔案:
Window.getComputedStyle()
<!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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/438232.html
標籤:javascript html css
上一篇:使用setAttribute后如何獲得絕對位置而不是“未定義”
下一篇:div的背景顏色
