2016-04-26 55 views
0

我想問一下,在html中我可以創建一個3切換按鈕。當我切換到左側時,條件1爲真。當我切換到右側時,條件2成立。在中間點,兩個條件是正確的。我想要有這樣的轉換,以確保至少總是有一個條件是真的。如何在html中創建3個切換按鈕

有沒有人有想法?非常感謝!

+0

純HTML/CSS,我的想法是創建一個單選按鈕組有三個輸入元素。然後以它看起來像你想要的開關的方式來設計它。 – Paul

回答

0

document.addEventListener('DOMContentLoaded', BtnCtrl); 
 
function BtnCtrl() { 
 
    var self = this; 
 
    var btns = document.querySelectorAll('.btn'); 
 
    
 
    //Just Set Defaults 
 
    var conditionA = true; 
 
    var conditionB = true; 
 
    
 
    self.syncDOM = function() { 
 
    document.getElementById('result').innerHTML = 'ConditionA: ' + conditionA + '; ConditionB:' + conditionB; 
 
    }; 
 
    
 
    self.onBtnClick = function(event) { 
 
    var condition = ((this.dataset || {}).condition || '').toLowerCase(); 
 
    
 
    switch(condition) { 
 
     case 'a': 
 
     conditionA = true; 
 
     conditionB = false; 
 
     break; 
 
     
 
     case 'b': 
 
     conditionB = true; 
 
     conditionA = false; 
 
     break; 
 
     
 
     default: 
 
     conditionA = true; 
 
     conditionB = true; 
 
    } 
 
    
 
    console.log('isValid ConditionA', conditionA); 
 
    console.log('isValid ConditionB', conditionB); 
 
    self.syncDOM(); 
 
    }; 
 

 
    self.syncDOM(); 
 
    for(var i = 0, btn; i < btns.length; i++) { 
 
    btn = btns[i]; 
 
    btn.addEventListener('click', self.onBtnClick.bind(btn)); 
 
    } 
 
}
#result { background: lightcoral; padding: 1em; margin: 5px; border: 1px solid red; }
<button class="btn" id="btnLeft" data-condition="a">LEFT</button> 
 
<button class="btn" id="btnMiddle">MIDDLE</button> 
 
<button class="btn" id="btnRight" data-condition="b">RIGHT</button> 
 

 
<div id=result></div>