事實上,我有 2 個盒子,id 名為 box1 和 box2。
我正在使用 J 查詢。
我的設計:
點擊box1 => 勾選box2背景色,如果是黑色就改成白色,否則就改成黑色。
我的硬代碼:
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
$( document ).ready(function() {
$("#box1").click(function(){
if ($('#box2').css({backgroundColor: 'white'})) {
$('#box2').css({backgroundColor: 'black'});
} else {
$('#box2').css({backgroundColor: 'white'});
}
});
});
uj5u.com熱心網友回復:
正如您將在此處的代碼段中看到的,jQuery 報告單元格的 RGB 值作為其背景顏色。對這類事情使用類要容易得多。在這種情況下,您可以只使用toggleClass()
此外,作為記錄,您的 IF 陳述句格式不正確:
if ($('#box2').css({backgroundColor: 'white'})) {
應該
if ($('#box2').css('background-color') == 'white') {
...但它會失敗,因為它實際上是rgb(255, 255, 255),不是white
$(document).ready(function() {
$("#box1").click(function() {
console.log('The background color of box 2 is: ', $('#box2').css('background-color'))
$("#box2").toggleClass('black');
});
});
div {
padding: 10px;
display:inline-block;
margin-right:10px;
border: 1px solid #ccc;
background-color: white;
}
.black {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box1"></div>
<div id="box2"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/461629.html
標籤:javascript html jQuery if 语句
