2016-11-08 32 views
0

我正在繪製應用程序。我有2個工具(鉛筆和橡皮)和一些顏色。 現在,當我檢查鉛筆我可以選擇一種顏色,但當我檢查橡皮擦,我想選擇一種顏色,我想再次檢查鉛筆工具,但橡皮擦工具保持選中狀態。更改後返回到默認複選框

任何指導都非常appriciated。

這裏有一個例子,代碼:

代碼:

HTML:

<!-- Pencil & Eraser --> 
<div class="graphic-tools"> 
    <!-- <div id="pencil" class="pencil"></div> --> 
    <input checked="checked" id="pencil" type="radio" name="tool" value="pencil" /> 
    <label class="tool pencil" for="pencil"></label> 
    <p class="">Potlood</p> 

    <!-- <div id="eraser" class="eraser"></div> --> 
    <input id="eraser" type="radio" name="tool" value="eraser" /> 
    <label class="tool eraser" for="eraser"></label> 
    <p>Gum</p> 
</div> 

<!-- colors --> 
<div id="colors" class="colors"></div> 

的JavaScript:

// Color swatches 
var colors = ['#000000', '#274e8d', '#6bb44b', '#e5cd46', '#e98b3a', '#d83538']; 

for (var i = 0, n=colors.length; i<n; i++) { 
    var swatch = document.createElement('div'); 
    swatch.className = 'swatch'; 
    swatch.style.backgroundColor = colors[i]; 
    swatch.addEventListener('click', setSwatch); 
    document.getElementById('colors').appendChild(swatch); 
} 

function setColor(color) { 
    context.fillStyle = color; 
    context.strokeStyle = color; 

    var active = document.getElementsByClassName('activeSwatch')[0]; 

    if (active) { 
     active.className = 'swatch'; 
    } 
} 

function setSwatch(e) { 
    //identify swatch 
    var swatch = e.target; 
    //set color 
    setColor(swatch.style.backgroundColor); 
    //give active class 
    swatch.className += ' activeSwatch'; 
} 

setSwatch({target: document.getElementsByClassName('swatch')[0] }); 


// Determine Tool 
document.getElementById('pencil').onchange = function() { 
    if (this.checked) { 
     tool = 'pencil'; 
     setSwatch({target: document.getElementsByClassName('swatch')[0] }); 
    } 
}; 
document.getElementById('eraser').onchange = function() { 
    if (this.checked) { 
     tool = 'eraser'; 
     setColor('#FFFFFF'); 
    } 
}; 

回答

1

不知道如果我理解正確的問題,所以我會嘗試重述它。

如果選擇橡皮擦並且用戶選擇了某種顏色,您是否希望自動選擇鉛筆工具?所以用戶不會用橡皮擦畫?

如果是這樣,那麼您應該修改setSwatch方法來檢查選定的工具是否實際上是鉛筆工具。如果沒有,您可能需要選擇它。有很多方法可以做到這一點,這裏有一個:

function setSwatch(e) { 
    //identify swatch 
    var swatch = e.target; 

    //ensure that pencil is selected 
    if (tool !== 'pencil') { 
     //just not sure which browsers support this 
     //also, this is not very good, since you'll 
     //switch color twice, so consider refactoring 
     document.getElementById('pencil').click(); 
    } 

    //set color 
    setColor(swatch.style.backgroundColor); 

    //give active class 
    swatch.className += ' activeSwatch'; 
} 
+0

是的,這是非常非常! –