【问题标题】:return to default check box after change更改后返回默认复选框
【发布时间】:2016-11-08 22:49:09
【问题描述】:

我正在开发绘图应用程序。我有 2 个工具(铅笔和橡皮)和一些颜色。 现在,当我检查铅笔时,我可以选择一种颜色,但是当我检查橡皮擦并想选择一种颜色时,我想再次检查铅笔工具,但橡皮擦工具保持选中状态。

非常感谢任何指导。

这是一个例子和代码:

代码:

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');
    }
};

【问题讨论】:

    标签: javascript html checkbox


    【解决方案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';
    }
    

    【讨论】:

    • 是的,就是这样!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多