最近,我在為CodePen Challenge做一個切換式的按鈕設置。我想給這個按鈕一個3D的外觀,所以我設置了一點JavaScript代碼來使用onclick實現這個功能。
var on = true
const green = document.getElementById('on')
const red = document.getElementById('off')
var greenOn = function() {
if (on == false) {
green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15) inset'
red.style.boxShadow = 'none'
var on = true;
}
}
var redOn = function() {
if (on == true) {
green.style.boxShadow = 'none'
red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
var on = false
}
}
下面是打包成一個代碼片段的代碼。
var on = true
const green = document.getElementById('on')
const red = document.getElementById('off')
var greenOn = function() {
if (on == false) {
green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15) inset'
red.style.boxShadow = 'none'
var on = true;
}
}
var redOn = function() {
if (on == true) {
green.style.boxShadow = 'none'
red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
var on = false
}
}
.on {
border-radius: 5px;
background-color: lime;
padding: 50px;
border: none;
}
.off {
border-radius: 5px;
background-color: red;
padding: 50px;
border: none;
}
.switch {
padding: 0;
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="switch">
<button class="on" id="on" onclick="greenOn()"></button>
<button class="off" onclick="redOn()" id="off"></button>
</div>
</body>
</html>
你的代碼有兩個問題
你在你的函數中設置了var on = true和var on = false,即使你已經對它進行了全局聲明,你在函數作用域中創建了一個新的變量on,這就是on不變的原因。 對于各自的功能,將其更改為on = false和on = true
應用于方框陰影屬性的值不是有效值。添加有效的屬性值以查看更改
var on = true;
const green = document.getElementById('on');
const red = document.getElementById('off');
var greenOn = function() {
if (!on) {
green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15)';
red.style.boxShadow = 'none';
on = true;
}
}
var redOn = function() {
if (on) {
green.style.boxShadow = 'none';
red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15)';
on = false;
}
}
.on {
border-radius: 5px;
background-color: lime;
padding: 50px;
border: none;
}
.off {
border-radius: 5px;
background-color: red;
padding: 50px;
border: none;
}
.switch {
padding: 0;
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="switch">
<button class="on" id="on" onclick="greenOn()"></button>
<button class="off" onclick="redOn()" id="off"></button>
</div>
</body>
</html>
您正在重新聲明與全局變量同名的局部變量:
var on = true
//...
var greenOn = function() {
//...
var on = true
}
所以在函數的范圍內,on不是最初全局聲明的on變量。它被一個新的局部變量隱藏了,這個變量只存在于這個函數中。變量聲明被掛起,但它的值沒有被掛起。所以它的值是未定義的,這種比較將失敗:
if (on == true) {
不要重新聲明變量,只需給它們賦值:
if (on == true) {
green.style.boxShadow = 'none'
red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
on = false // <--- here
}
另外,我強烈建議你養成用分號結束你的陳述的習慣。雖然JavaScript允許省略這些并執行自動分號插入,但這是一個非常常見的錯誤來源。