【问题标题】:How can I create checkbox for images using jquery如何使用 jquery 为图像创建复选框
【发布时间】:2011-11-06 13:24:23
【问题描述】:

我试图为图像创建一个复选框,如果我们有多个图像,我可以在继续之前选择 3 或 4 个图像。我见过这种东西,但我不知道如何使用 jquery 创建相同的东西。

例如,在这张图片中,我想提供一个选项,如果有人点击该图片,它就会被选中。用户可以像这样选择多个图像。可以使用jquery吗?或者是否有一个插件可以帮助我实现这一点。

【问题讨论】:

  • 谷歌搜索 jquery image checkbox 给了我一些有希望的结果。他们不适合你吗?
  • 这完全取决于您的意图。当然,您可以有复选框,只需添加它们。在不知道您的页面结构是什么、什么需要动态以及您打算如何处理这些信息的情况下,这里没有太多问题,

标签: jquery html jquery-ui jquery-plugins


【解决方案1】:

这可能足以满足您的需求。当然,您可以根据自己的喜好编辑脚本和 CSS:

$('.image-checkbox-container img').live('click', function(){
    if(!$(this).prev('input[type="checkbox"]').prop('checked')){
        $(this).prev('input[type="checkbox"]').prop('checked', true).attr('checked','checked');
        this.style.border = '4px solid #38A';
        this.style.margin =' 0';
    }else{
        $(this).prev('input[type="checkbox"]').prop('checked', false).removeAttr('checked');
        this.style.border = '0';
        this.style.margin = '4px';
    }
});

CSS:

.image-checkbox-container input[type="checkbox"]{
    display: none;
}

.image-checkbox-container img{
    border: 0;
    margin: 4px;
}

Here is a JSFIddle Example

【讨论】:

  • 自 javascript 1.9 以来 .live() 调用已停止,因此要在现代环境中使用它,您需要将 .live 替换为 .on - 当您发现问题时很简单,但这让我很困惑好一阵子。
【解决方案2】:

许多可能的实现之一。在这里,我假设您事先生成了一个图像列表和相应的复选框(不是使用 javascript)。

HTML(截断):

<div id="selectable_images">
   <img src="/image1.jpg" rel="ch_image_1"/>
   <input style="display:none" type="checkbox" id="ch_image_1" value="image1.jpg"/>

   <img src="/image2.jpg" rel="ch_image_2"/>
   <input style="display:none" type="checkbox" id="ch_image_2" value="image2.jpg"/>

   <img src="/image3.jpg" rel="ch_image_3"/>
   <input style="display:none" type="checkbox" id="ch_image_3" value="image3.jpg"/>
</div>

JS(jQuery):

$(function() {
    $("#selectable_images img").click(function() {
       var $this = $(this);
       if ($this.hasClass('selected')) {
           $("#"+this.rel).attr('checked', false);
           $this.removeClass('selected');
       } else {
           $("#"+this.rel).attr('checked', true);
           $this.addClass('selected');
       }
    })
}

通过单击图像,相应的复选框将被切换。选定的图像将获得“选定”类。

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    相关资源
    最近更新 更多