【发布时间】:2020-11-11 04:38:08
【问题描述】:
我有一个小型 html 应用程序,它只会将 html 正文的背景颜色更改为随机生成的十六进制颜色。我遇到的问题是,当我单击按钮时,新的背景颜色不仅出现在正文上,而且还会影响按钮的背景颜色。在我的 css 中,我定义了按钮的背景颜色应该始终相同。
您知道如何保持按钮的背景颜色始终相同且独立于正文吗?
Bad background color inside of the button
这是我的代码:
var button = document.getElementById('btn')
function createColorSegment(value) {
const Segment = {}
Segment.value = value
return Segment
}
button.onclick = function() {
const r1 = createColorSegment(undefined)
const r2 = createColorSegment(undefined)
const g1 = createColorSegment(undefined)
const g2 = createColorSegment(undefined)
const b1 = createColorSegment(undefined)
const b2 = createColorSegment(undefined)
function HexadecimalColor(colorSegment) {
var numberOfColorSegment = Math.floor(Math.random() * 16)
if (numberOfColorSegment == 10) {
colorSegment.value = 'a'
}
else if (numberOfColorSegment == 11) {
colorSegment.value = 'b'
}
else if (numberOfColorSegment == 12) {
colorSegment.value = 'c'
}
else if (numberOfColorSegment == 13) {
colorSegment.value = 'd'
}
else if (numberOfColorSegment == 14) {
colorSegment.value = 'e'
}
else if (numberOfColorSegment == 15) {
colorSegment.value = 'f'
}
else {
colorSegment.value = numberOfColorSegment
}
}
HexadecimalColor(r1)
HexadecimalColor(r2)
HexadecimalColor(g1)
HexadecimalColor(g2)
HexadecimalColor(b1)
HexadecimalColor(b2)
console.log(r1.value)
console.log(r2.value)
console.log(g1.value)
console.log(g2.value)
console.log(b1.value)
console.log(b2.value)
var HexColor = "#" + r1.value + r2.value + g1.value + g2.value + b1.value + b2.value
console.log(HexColor)
document.getElementsByTagName('body')[0].style.backgroundColor = HexColor
document.getElementsByClassName('hex-color-name')[0].innerText = "HEX COLOR: " + HexColor
}
* {
padding: 0;
margin: 0;
}
body {
display: flex;
justify-content: center;
}
.container {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.hex-color-name {
font-family: 'Trebuchet MS';
font-weight: bold;
font-size: 36px;
padding-bottom: 10px;
text-transform: uppercase;
}
.button {
position: absolute;
right: 50%;
transform: translateX(+50%);
height: 40px;
width: 100px;
border-radius: 4px;
font-size: 18px;
font-weight: bold;
cursor: pointer;
background-color:rgba(0, 0, 0, 0.6);
color: white;
border: 2px solid rgba(128, 128, 128, 0.8);
}
.button:hover {
color: white;
background-color:rgba(0, 0, 0, 0.7);
}
.button:focus {
outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script defer src="script.js"></script>
<title>Project2</title>
</head>
<body>
<div class="container">
<div class="hex-color-name">HEX COLOR:</div>
<button type="button" id="btn" class="button">Click me!</button>
</div>
</body>
</html>
【问题讨论】:
-
当使用不透明度时会发生这种情况。
标签: javascript html css