gpt4 book ai didi

JavaScript - 交换颜色

转载 作者:太空宇宙 更新时间:2023-11-03 19:36:17 27 4
gpt4 key购买 nike

在此 JavaScript 示例中,当用户单击“更改颜色”按钮时,它需要交换两个 div 元素的颜色。但事实并非如此。

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
#first
{
border-radius: 100%;
background-color: red;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}

#second
{
border-radius: 100%;
background-color: green;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<button id="color">Change colors</button>
<br />

<div id="first">Random text.</div>
<div id="second">Random text.</div>
<div id="third"></div>

<script type="text/javascript">
document.getElementById('color').onclick = function () {
var divColor = document.getElementById('first').style.backgroundColor;
document.getElementById('first').style.backgroundColor = document.getElementById('second').style.backgroundColor.toString();
document.getElementById('second').style.backgroundColor = divColor.toString();
}
</script>
</body>
</html>

但是当我稍微改变它并从 <style> 中删除 'background-color' 时并将其放在 <div> 内然后它就开始工作了。

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
#first
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}

#second
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<button id="color">Change colors</button>
<br />

<div id="first" style="background-color: red;">Random text.</div>
<div id="second" style="background-color: green;">Random text.</div>

<script type="text/javascript">
document.getElementById('color').onclick = function () {
var divColor = document.getElementById('first').style.backgroundColor;
document.getElementById('first').style.backgroundColor = document.getElementById('second').style.backgroundColor.toString();
document.getElementById('second').style.backgroundColor = divColor.toString();
}
</script>
</body>
</html>

那么当'background-color'在<style>范围内时,有什么方法可以解决这个问题吗?在 <head>

最佳答案

Element.style 仅适用于元素的 style 属性中的样式。如果你想要计算样式,它会影响样式表等...

var firstElem = document.getElementById('first'),
secondElem = document.getElementById('second'),
firstBackground = window.getComputedStyle(firstElement).backgroundColor,
secondBackground = window.getComputedStyle(secondElement).backgroundColor;
firstElem.style.backgroundColor = secondBackground;
secondElem.style.backgroundColor = firstBackground;

这应该交换两种颜色,无论它们在哪里定义。

关于JavaScript - 交换颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39518836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com