【发布时间】:2017-04-24 09:12:51
【问题描述】:
我在 jqueryscript.net link 上发现了这个名为 BlueToggleButton 的非常有用的脚本
基本上它将复选框转换为您选择的自定义按钮。它工作得很好,尽管如果有办法对单选按钮做同样的事情会更好。我完全不喜欢 jQuery 和 Javascript,所以我真的不知道从哪里开始。我试图用“radio”替换代码中的“checkbox”字符串,但这似乎没有奏效。
脚本如下所示。它连接到一个 css 文件,您可以在其中设置按钮样式和一些要在按钮内使用的图像。
$(function ($) {
$.widget("toggle.toggleButton", {
options : {
text : "Toggle",
toggleOnColor : "green",
onTitle : "On",
offTitle : "Off",
onImg: "toggleON.png",
offImg: "toggleOFF.png",
change : null
},
_create : function() {
var id = this.element.attr("id");
var checkBoxStyle = this.element.attr("style");
this.element.css({
"display" : "none"
});
this.checkboxButton = $("<label>", {
text : this.options.text,
"class" : "toggleButton",
"for" : id,
"style" : checkBoxStyle
});
this.element.after(this.checkboxButton);
if (this.element.is(":checked")) {
this.element
.next("label").css({ "background" : this.options.toggleOnColor, "color" : "white" })
.prop({ "title" : this.options.onTitle })
.prepend('<span class="toggle-img" style="background:url(' + this.options.onImg + '); background-position:center;" />');
} else {
this.element
.next("label").css({ "background" : "", "color" : "grey" })
.prop({ "title" : this.options.offTitle })
.prepend('<span class="toggle-img" style="background:url(' + this.options.offImg + '); background-position:center;" />');
};
this._on(this.element, {
"change" : function(event) {
if (this.element.is(":checked")) {
this.element
.next("label").css({ "background" : this.options.toggleOnColor, "color" : "white" })
.prop({ "title" : this.options.onTitle })
.find(".toggle-img")
.css({"background" : "url(" + this.options.onImg + ")" });
} else {
this.element
.next("label").css({ "background" : "", "color" : "grey" })
.prop({ "title" : this.options.offTitle })
.find(".toggle-img")
.css({"background" : "url(" + this.options.offImg + ")" });
};
}
});
}
});
}(jQuery));
编辑:这是与它一起使用的 html:
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" id="toggle-button">
<input type="checkbox" id="toggle-button2">
<script>
$("#toggle-button").toggleButton({text : "Checked button"});
$("#toggle-button2").toggleButton({text : "Un-checked button"});
</script>
有什么想法吗?我试图与创作者取得联系,但没有得到回应。提前非常感谢!
【问题讨论】:
-
现有脚本正在将复选框转换为按钮。我希望脚本对单选按钮执行相同的操作,以便单选按钮同样转换为按钮。我试图通过用“radio”替换“checkbox”字符串来更改代码,但这不起作用,它什么也没做。应该吗?
标签: javascript jquery html checkbox radio-button