javascript 用图像替换复选框并更新 onClick(可能是 jQuery?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4894101/
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
Replacing Checkbox with image and update onClick (possibly jQuery?)
提问by Parker
Is there a way that I can have an image replace a checkbox, and when someone clicks on it, it selects it, and changes the image to another image like a "checked" image?
有没有办法让图像替换复选框,当有人点击它时,它会选择它,并将图像更改为另一个图像,如“选中”图像?
So essentially:
所以本质上:
[heart-icon] Health and Fitness
[heart-icon] 健康与健身
user clicks on it
用户点击它
[check-icon] Health and Fitness
[勾选图标] 健康与健身
and now that area is selected
现在该区域已被选中
回答by Jeff
There are definitely scripts/plugins available to do this. I've not used any of them so I can't recommend one specifically, but here's an example:
肯定有脚本/插件可以做到这一点。我没有使用过它们中的任何一个,所以我不能特别推荐一个,但这里有一个例子:
http://www.itsalif.info/content/ezmark-jquery-checkbox-radiobutton-plugin
http://www.itsalif.info/content/ezmark-jquery-checkbox-radiobutton-plugin
回答by Adi
I would try this plugin: SimpleImageCheck http://www.jkdesign.org/imagecheck/
我会试试这个插件:SimpleImageCheck http://www.jkdesign.org/imagecheck/
Code to customize the checkbox looks simple:
自定义复选框的代码看起来很简单:
$('#checkbox').simpleImageCheck({
image: 'unchecked.png',
imageChecked: 'check.png'
afterCheck: function(isChecked) {
if (isChecked) {
// do something
}
}
});
回答by Edakos
No need of plugins nor JQuery:
不需要插件或 JQuery:
<span onclick="changeCheck(this)">
<img src="http://www.clker.com/cliparts/e/q/p/N/s/G/checkbox-unchecked-md.png">
<img src="http://www.clker.com/cliparts/4/h/F/B/m/4/nxt-checkbox-checked-ok-md.png">
<input type="checkbox" name="chk">
</span>
<script>
function changeCheck(target)
{
chk = target.lastElementChild;
chk.checked = !chk.checked;
target.children[+ chk.checked].style.display = '';
target.children[1 - (+ chk.checked)].style.display = 'none';
}
function initCheck()
{
chk = document.getElementsByName('chk')[0];
chk.style.display = 'none';
chk.parentNode.children[1 - (+ chk.checked)].style.display = 'none';
}
initCheck();
</script>

