jQuery 如何显示图像代替复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16352864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:59:41  来源:igfitidea点击:

How to display image in place of checkbox?

jquerycsshtml

提问by Dhwani

I want to display green checked image when checkbox is checked and when not checked empty box. I tried to put checkbox in div and set div's background but it is not helping me out. Any idea what to do? Below is the output I want.

我想在选中复选框时显示绿色选中的图像,未选中时显示为空框。我试图将复选框放在 div 中并设置 div 的背景,但它没有帮助我。知道该怎么做吗?下面是我想要的输出。

Image

图片

回答by Anujith

Like this with little jQuery and css: DEMO

像这样用一点 jQuery 和 css:DEMO

<div class="checkbox">
</div>

.checkbox{
   width: 23px;
   height: 21px;
   background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 0 50%
}
.checked{
   background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 80% 50%
}

$(".checkbox").click(function(){
    $(this).toggleClass('checked')
});

回答by asim-ishaq

As others have said, you can use a proxy element (div) and change checkbox state checked/unchecked when the div is clicked. Following is the working example of exactly what you require: (i have used simple javascript so that the readers can understand it quickly)

正如其他人所说,您可以使用代理元素 (div) 并在单击 div 时更改选中/取消选中的复选框状态。以下是您所需要的工作示例:(我使用了简单的 javascript 以便读者可以快速理解它)

Step by step guide:

分步指南:

1) First of all create two css classes one for checked state and one for unchecked state:

1)首先创建两个css类,一个用于选中状态,一个用于未选中状态:

.image-checkbox {
    background:url(unchecked.png);
    width:30px;
    height:30px;
}

.image-checkbox-checked {
    background:url(checked.png);
    width:30px;
    height:30px;
}

2) Create the HTML for DIVs and Checkboxes. The idea is that for each checkbox (input type=checkbox) we will have a div. The id of the div will be suffixed by the word proxy so that we can identify it. Also for each proxy div we will assign the initial class .image-checkbox. Let say we create two checkboxes:

2) 为 DIV 和复选框创建 HTML。这个想法是,对于每个复选框(输入类型=复选框),我们将有一个 div。div的id后面会加上proxy这个词,这样我们就可以识别了。同样对于每个代理 div,我们将分配初始类 .image-checkbox。假设我们创建了两个复选框:

<div id="checkbox1_proxy" class="image-checkbox" />
<div id="checkbox2_proxy" class="image-checkbox" />

Originl Checkboxes (hide it with style property [visibility: hidden])

原始复选框(使用样式属性隐藏它[可见性:隐藏])

<input id="checkbox1" name="checkbox1" type="checkbox"  />
<input id="checkbox2" name="checkbox2" type="checkbox"  />

3) Now we will need some javascript code to set checkbox to checked/unchecked when the proxy elements (DIVs) are clicked. Also we need to change the background image of Proxy divs according to the current state of checkbox. We can call a function to attach event handlers when the document is loaded:

3) 现在我们需要一些 javascript 代码来在单击代理元素 (DIV) 时将复选框设置为选中/取消选中。此外,我们需要根据复选框的当前状态更改代理 div 的背景图像。我们可以在加载文档时调用一个函数来附加事件处理程序:

<body onload="load()">

<script type="text/javascript">
function load() {
    var all_checkbox_divs = document.getElementsByClassName("image-checkbox");

    for (var i=0;i<all_checkbox_divs.length;i++) {

        all_checkbox_divs[i].onclick = function (e) {
            var div_id = this.id;
            var checkbox_id =div_id.split("_")[0];
            var checkbox_element = document.getElementById(checkbox_id);

            if (checkbox_element.checked == true) {
                checkbox_element.checked = false;
                this.setAttribute("class","image-checkbox");
            } else {
                checkbox_element.checked = true;
                this.setAttribute("class","image-checkbox-checked");
        }

        };
    }

}
</script>

Thats all... i hope it helps

就是这样...我希望它有帮助

回答by Moritz Friedrich

Someone stumbling over this while googling? Take this CSS-only approach into consideration:

有人在谷歌搜索时绊倒了吗?考虑这种仅使用 CSS 的方法:

input[type=checkbox] {
    display: block;
    width: 30px;
    height: 30px;
    -webkit-appearance: none;
    outline: 0;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
}

input[type=checkbox]:not(:checked) {
    background-image: url(unchecked.svg);
}

input[type=checkbox]:checked {
    background-image: url(checked.svg);
}





See this example:

看这个例子:

input[type=checkbox] {
    display: block;
    width: 30px;
    height: 30px;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-appearance: none;
    outline: 0;
}
input[type=checkbox]:checked {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path id="checkbox-3-icon" fill="#000" d="M81,81v350h350V81H81z M227.383,345.013l-81.476-81.498l34.69-34.697l46.783,46.794l108.007-108.005 l34.706,34.684L227.383,345.013z"/></svg>');
}
input[type=checkbox]:not(:checked) {
    background-image: url('data:image/svg+xml;utf8,<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"> <path id="checkbox-9-icon" d="M391,121v270H121V121H391z M431,81H81v350h350V81z"></path> </svg>');
}
<input type="checkbox" id="check" />
<div></div>

回答by sylwia

One solution is to make div instead of checkbox and set a background as you want and then use js to make behaviour of the div as it was checkbox, so add onClick actions.

一种解决方案是制作 div 而不是复选框并根据需要设置背景,然后使用 js 使 div 的行为与复选框一样,因此添加 onClick 操作。

回答by ling

Inspired by @asim-ishaq's answer, here is a jquery based solution that also takes into account the fact that the user can toggle the checkbox by clicking on the label tag:

受到@asim-ishaq 的回答的启发,这是一个基于 jquery 的解决方案,它也考虑到用户可以通过单击标签标签来切换复选框的事实:

<style>
    div.round-checkbox {
        background: transparent url(/css/icons-sprite.png) no-repeat -192px -72px;
        height: 24px;
        width: 24px;
        display: inline-block;

    }

    div.round-checkbox.checked {
         background: transparent url(/css/icons-sprite.png) no-repeat -168px -72px;
     }

    input.round-checkbox {
        display: none;
    }
</style>

<div class="round-checkbox" data-id="subscribe-promo-1"></div>
<input type='checkbox' class="round-checkbox" name='subscribe' value='1' id="subscribe-promo-1" />
<label for="subscribe-promo-1">I want to subscribe to offers</label>


<script>
    $(document).ready(function () {
        var jRoundCheckbox = $('input.round-checkbox');

        /**
         * Init: if the input.checkbox is checked, show the checked version of the div.checkbox,
         * otherwise show the unchecked version
         */
        jRoundCheckbox.each(function () {
            var id = $(this).attr('id');
            if ($(this).prop('checked')) {
                $('.round-checkbox[data-id="' + id + '"]').addClass("checked");
            }
            else {
                $('.round-checkbox[data-id="' + id + '"]').removeClass("checked");
            }
        });

        /**
         * If the user clicks the label, it will check/uncheck the input.checkbox.
         * The div.checkbox should reflect this state
         */
        jRoundCheckbox.on('change', function () {
            var id = $(this).attr('id');
            $('.round-checkbox[data-id="' + id + '"]').toggleClass("checked");
            return false;
        });

        /**
         * When the user clicks the div.checkbox, it toggles the checked class;
         * also, the input.checkbox should be synced with it
         */
        $('div.round-checkbox').on('click', function () {
            var id = $(this).attr('data-id');
            var jInput = $('#' + id);
            jInput.prop("checked", !jInput.prop('checked'));
            $(this).toggleClass("checked");
            return false;
        });
    });
</script>

回答by abdullah

Here is another example. Works fine on Ionic v1. CSS

这是另一个例子。在 Ionic v1 上运行良好。CSS

input[type=checkbox] {
    display: none;
}

 :checked+img {
    content: url('/img/active.png');
}

HTML

HTML

    <label>
    <input type="checkbox" ng-model="anything">
    <img style="height:30px;" src="img/deactive.png">
    </label>
    <span>{{anything}}</span>

回答by Lance Larsen - Microsoft MVP

Know this is an older thread -- but needed a solution to converting checkboxes to images. :) Here's a jQuery version that works great for me - wanted to share.

知道这是一个较旧的线程 - 但需要一个将复选框转换为图像的解决方案。:) 这是一个非常适合我的 jQuery 版本 - 想分享。

function setCheckboxImageSrc(checkbox, image, checkedUrl, uncheckedUrl) {
    if (checkbox.is(":checked")) {
        image.attr("src", checkedUrl);
    } else {
        image.attr("src", uncheckedUrl);
    }
}

function setCheckboxImage(checkboxObj, className, checkedUrl, uncheckedUrl) {
    checkboxObj.hide();

    var $image = $("<img src='" + checkedUrl + "' />").insertAfter(checkboxObj);
    setCheckboxImageSrc(checkboxObj, $image, checkedUrl, uncheckedUrl);

    $image.click(function () {
        var $checkbox = $image.prev("." + className);
        $checkbox.click();
        setCheckboxImageSrc($checkbox, $image, checkedUrl, uncheckedUrl);
    });
}

$(".checkboxUp").each(function () {
    setCheckboxImage($(this), "checkboxUp", "../../../images/DirectionUpChecked.png", "../../../images/DirectionUpUnchecked.png");
});

$(".checkboxDown").each(function () {
    setCheckboxImage($(this), "checkboxDown", "../../../images/DirectionDownChecked.png", "../../../images/DirectionDownUnchecked.png");
});