我正在尝试创建一个小jQuery开关插件。
这是我的代码:
(function($){
$.fn.slideSwitch = function (options) {
var settings = $.extend({
defaultSide: "left",
backgroundColor: "red",
toggleSize: 30,
toggleColor: "white",
speed: 100
}, options );
return this.each(function() {
$this = $(this);
var gap = Math.round(settings.toggleSize * 0.03);
if (gap < 1) {gap = 1}
$this.css({
width: (settings.toggleSize * 2) + "px",
backgroundColor: settings.backgroundColor,
borderRadius: settings.toggleSize + "px",
overflow: "hidden",
padding: gap + "px"
})
var marginLeft = 0;
if (settings.defaultSide == "right") {
marginLeft = settings.toggleSize;
}
var toggle = $("<div>").addClass("ssToggle").css({
width: settings.toggleSize,
height: settings.toggleSize,
borderRadius: settings.toggleSize,
backgroundColor: settings.toggleColor,
float: settings.defaultSide,
marginLeft: marginLeft
});
$this.html(toggle);
$this.click(function() {
var tggl = $(this).find(".ssToggle");
console.log("margin-left:", tggl.css("margin-left"));
if (parseInt(tggl.css("margin-left")) == 0) {
console.log("moving to the right");
tggl.animate({ "margin-left": settings.toggleSize + "px" }, settings.speed);
if (settings.defaultSide == "right") { $(this).trigger("switchedOn"); }
} else {
console.log("moving to the left");
tggl.animate({ "margin-left": 0 }, settings.speed);
if (settings.defaultSide == "left") { $(this).trigger("switchedOn"); }
}
$(this).trigger("switched");
})
});
};
}(jQuery));
$(function() {
$(".ssSwitch").slideSwitch({
toggleSize: 30,
speend: 40,
defaultSide: "right"
}).on("switchedOn", function(e) {
console.log("switched on!");
});
});
<div class="ssSwitch"></div>
现场演示:https://jsfiddle.net/cutsomeat/zd6ucc5u/
当我将defaultSide选项设置为“left”时,它可以正常工作。但是,当我将defaultSide选项设置为“right”时,会发生一些奇怪的事情。 css“margin-left”属性已经改变了,但你没有看到元素的任何移动。 css将不断来回变换,但元素将保持原始位置。
任何人都可以向我解释为什么会这样吗?