2016-04-13 25 views
0

jQueryスイッチプラグインを作成しようとしています。ここでjQueryアニメーションはCSSを変更しますが、アニメ化しません。

は私のコードです:

(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) { 
 
    \t console.log("switched on!"); 
 
    }); 
 
});
<div class="ssSwitch"></div>

ライブデモ:https://jsfiddle.net/cutsomeat/zd6ucc5u/

私はそれが正常に動作し、 "左" に設定defaultSideオプションを持っている場合。しかし、defaultSideオプションが "right"に設定されていると、何か変なことが起こります。 css "margin-left"プロパティは想定されていたように変更されましたが、要素の動きは表示されません。 CSSは前後に変化し続けますが、要素は元の位置にとどまります。

誰も私になぜこれが起こっているのか説明できますか?この行をコメントアウトすることで

+0

ヒントを参照してください:ザ・スタックスニペットは、コードブロックは、右ここで、オンサイト、ライブデモを行うことが十分に可能であるとして、あなたが使用しています。 –

答えて

1

、すべて正常に動作します:

float: settings.defaultSide, 

はそれを試してみてください。Demo here

1

あなたは余裕を作るあなたの「ボタン」要素、フロート「右」、上の冗長なスタイリングを持っていますあなたは無関係に設定しています。行を削除してください

float: settings.defaultSide, 

これは問題ありません。

更新fiddle

関連する問題