【问题标题】:Toggle opacity change to checkbox images将不透明度更改为复选框图像
【发布时间】:2013-11-10 10:57:59
【问题描述】:

一旦选中复选框并将默认不透明度设置为 0.5(半不透明度),我想将复选框图像的不透明度更改为 1.0(正常不透明度)。但是我对 JavaScript 和 CSS 的编码一无所知。

<input type="checkbox" id="n1" name="n1" style="display: none;" /><label for="n1"><img src="images/n1.png" width="20" height="20" /></label>
<input type="checkbox" id="n2" name="n2" style="display: none;" /><label for="n2"><img src="images/n2.png" width="20" height="20" /></label>

...

<input type="checkbox" id="n50" name="n50" style="display: none;" /><label for="n2"><img src="images/n50.png" width="20" height="20" /></label>

【问题讨论】:

    标签: javascript html css checkbox


    【解决方案1】:

    这是一种使用 无需 JS,只需 CSS:

    的方法:
    label img {
        opacity : 0.5;
    }
    input[type=checkbox]:checked + label img {
        opacity : 1;
    }
    

    演示:http://jsfiddle.net/W2hHg/

    注意它使用adjacent sibling selector +,因此它依赖于紧跟在相应复选框元素之后的标签元素。

    但是如果你想支持 IECSS :checked selector 我仍然建议定义上面的 label img 类来设置默认不透明度,然后在选中时定义以下类:

    label.checked img {
        opacity : 1;
    }
    

    ...然后使用 JS 添加和删除该类:

    document.onclick = function(e) {
        if (!e) e = window.event;
        var el = e.target || e.srcElement;
        if (el.type === "checkbox") {
            if (el.checked)
                el.nextSibling.className += " checked";
            else
                el.nextSibling.className = el.nextSibling.className.replace(/\bchecked\b/,"");
        }
    };
    

    演示:http://jsfiddle.net/W2hHg/2/

    【讨论】:

    • 非常感谢!你帮了我很多!
    【解决方案2】:

    你可以试试这个,

     $(document).ready(function(e) {
        $('input:checkbox').click(function(){    
    
         var ImgId = 'img_'+$(this).attr('id');              
           if( $(this).is(':checked')) {
               $("#"+ImgId).css('opacity', '0.5');
             } else {
                $("#"+ImgId).css('opacity', '1');
              }             
    
    
            });//end click
     });//end ready
    

    HTML:

        <input type="checkbox" id="n1" name="n1"  /><label for="n1"><img src="images/n1.png" width="20" height="20" id='img_n1' /></label>
        <input type="checkbox" id="n2" name="n2" /><label for="n2"><img src="images/n2.png" width="20" height="20"  id='img_n2'/></label>
    

    【讨论】:

    • 为什么需要更改 html?您可以使用$('input:checkbox') 选中复选框,然后使用$('label[for="' + this.id + '"]') 选择适当的img
    • 你说得对,$('label[for="' + this.id + '"]') 我们可以使用它,但在他的问题中,他没有给予label for 属性的重要性。这就是我这样包裹的原因。
    猜你喜欢
    • 2012-07-18
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 2012-09-18
    • 2016-09-02
    相关资源
    最近更新 更多