将class元素返回默认值

时间:2012-10-17 18:34:41

标签: javascript jquery html

我有4个箭头,每个箭头都移动了棋子元素 现在我想创建一个重置按钮,将该片段返回到默认位置

//piece object
var piece = {};
piece.el = $('#piece');
piece.moveDelta = function(dx, dy){
    var pos = this.el.position();
    this.el.css('left', pos.left+dx);
    this.el.css('top', pos.top+dy);
};
$(document).ready(function(){
    //init deltas
    $('#btn-up').data('dx', 0).data('dy', -100);
    $('#btn-left').data('dx', -100).data('dy', 0);
    $('#btn-right').data('dx', 100).data('dy', 0);
    $('#btn-down').data('dx', 0).data('dy', 100);
    //assign click event
    $('.btn-arrow').click(function(){
        piece.moveDelta($(this).data('dx'), $(this).data('dy'));
    });
});

2 个答案:

答案 0 :(得分:2)

   //piece object
var piece = {};

var defaultX = null;
var defaultY = null;

piece.el = $('#piece');
piece.moveDelta = function(dx, dy){
    var pos = this.el.position();
    if(defaultX === null && defaultY === null ){
         defaultX = pos.left;
         defaultY = pos.top;
    }
    this.el.css('left', pos.left+dx);
    this.el.css('top', pos.top+dy);
};
piece.reset = function () {
   this.el.css('left', defaultX);
   this.el.css('top', defaultY);
};
$(document).ready(function(){
    //init deltas
    $('#btn-up').data('dx', 0).data('dy', -100);
    $('#btn-left').data('dx', -100).data('dy', 0);
    $('#btn-right').data('dx', 100).data('dy', 0);
    $('#btn-down').data('dx', 0).data('dy', 100);


    //assign click event
    $('.btn-arrow').click(function(){
        piece.moveDelta($(this).data('dx'), $(this).data('dy'));
    });
    $("#btn-reset").click(function(){
       piece.reset();
    });

});

您可以使用上面定义的reset方法。 Fiddle

答案 1 :(得分:1)

您可以将CSS属性设置为空字符串以重置它们:http://jsfiddle.net/myJCq/

piece.reset = function() {
    this.el.css({ left: '', top: '' });
};