2015-11-06 2 views
0

Сбой при добавлении step и heading динамически и попробуйте поменять свое положение, используя стрелки вверх и вниз для перемещения вверх и вниз соответственно.Сбой при анимации динамически добавленных элементов

Html:

<div class="makeit_steps"></div> 
<div class="row margin-top"> 
    <div class="col-md-12"> 
     <div class="col-md-2"> 
      <span class="glyphicon glyphicon-plus-sign"></span> 
      <span id="add-step" class="add-new">Add Step</span> 
     </div> 
     <div class="col-md-2"> 
      <span class="glyphicon glyphicon-plus-sign"></span> 
      <span id="add-heading" class="add-new">Add Heading</span> 
     </div> 
    </div> 
</div> 

JavaScript:

Добавление шаг динамически:

$('#add-step').click(function() { 
$('.makeit_steps').append('<div class="row moving"><div class="col-md-12"><span class="steps">Step</span><span><textarea class="form-control" rows="3" cols="105"></textarea></span><span class="glyphicon glyphicon-circle-arrow-up"></span><span class="glyphicon glyphicon-circle-arrow-down"></span><span class="step_remove">X</span></div></div>'); 
$('.step_remove').click(function() { 
    $(this).closest('.moving').remove(); 
}); 
$(".glyphicon-circle-arrow-up").click(function() { 
    var $current = $(this).closest('.moving') 
    var $previous = $current.prev('.moving'); 
    distance = $current.outerHeight(); 
    if ($previous.length !== 0) { 

     $.when($current.animate({ 
      top: -distance 
     }, 600), 
     $previous.animate({ 
      top: distance 
     }, 600)).done(function() { 
      $previous.css('top', '0px'); 
      $current.css('top', '0px'); 
      $current.insertBefore($previous); 
     }); 
    } 
    return false; 
}); 

$(".glyphicon-circle-arrow-down").click(function() { 
    var $current = $(this).closest('.moving') 
    var $next = $current.next('.moving'); 
    distance = $current.outerHeight(); 
    if ($next.length !== 0) { 
     $.when($current.animate({ 
      top: distance 
}, 600), 
$next.animate({ 
    top: -distance 
}, 600)).done(function() { 
    $next.css('top', '0'); 
    $current.css('top', '0'); 
      $current.insertAfter($next); 
      animating = false; 
     }); 
    } 
    return false; 
}); 
}); 

Добавление заголовок динамически:

$('#add-heading').click(function() { 
$('.makeit_steps').append('<div class="row moving"><div class="col-md-12"><span class="step_heading">Heading</span><span><input type="text" ></input></span><span class="glyphicon glyphicon-circle-arrow-up"></span><span class="glyphicon glyphicon-circle-arrow-down"></span><span class="step_remove">X</span></div></div>') 
$('.step_remove').click(function() { 
    $(this).closest('.row').remove(); 
}); 
var animating = false; 
$(".glyphicon-circle-arrow-up").click(function() { 
    if (animating) { 
     return; 
    } 
    var $current = $(this).closest('.moving') 
    var $previous = $current.prev('.moving'); 
    distance = $current.outerHeight(true); 
    if ($previous.length !== 0) { 

     animating = true; 
     $.when($current.animate({ 
      top: -distance 
     }, 600), 
     $previous.animate({ 
      top: distance 
     }, 600)).done(function() { 
      $previous.css('top', '0px'); 
      $current.css('top', '0px'); 
      $current.insertBefore($previous); 
      animating = false; 
     }); 
    } 

}); 
$(".glyphicon-circle-arrow-down").click(function() { 
    if (animating) { 
     return; 
    } 
    var $current = $(this).closest('.moving') 
    var $next = $current.next('.moving'); 
    distance = $current.outerHeight(); 
    if ($next.length !== 0) { 

     animating = true; 
     $.when($current.animate({ 
      top: distance 
}, 600), 
$next.animate({ 
    top: -distance 
}, 600)).done(function() { 
    $next.css('top', '0'); 
    $current.css('top', '0'); 
      $current.insertAfter($next); 
      animating = false; 
     }); 
    } 
}); 
}); 

CSS

.margin-top { 
    margin-top:20px; 
} 
.glyphicon.glyphicon-circle-arrow-up, .glyphicon.glyphicon-circle-arrow-down { 
    font-size:30px; 
    margin-left:25px; 
    cursor:pointer; 
} 
.add-new { 
    color:#007acc; 
    cursor:pointer; 
} 
.steps { 
    font-size:16px; 
    padding-left:30px; 
    padding-right:20px; 
} 
.step_remove { 
    font-size:16px; 
    color:#007acc; 
    margin-left:15px; 
    cursor:pointer; 
} 
.step_heading { 
    padding-left:15px; 
    font-size:16px; 
    padding-right:10px; 
} 
.makeit_steps { 
    position: relative; 
} 
.makeit_steps .moving { 
    position:relative; 
} 
.moving span { 
    display:inline-block; 
    vertical-align: middle; 
} 

Fiddle: Here

ответ

1

Проблемы с кодом в настоящее время является то, что оно является обязательным событием щелчка несколько раз на стрелки вверх и вниз (существующие) всякий раз, когда вы создаете динамически новенький.

Для того, чтобы прикрепить событие щелчка только на вновь добавленный элементе вы должны создать объект нового элемента, который будет добавлен, а затем вы можете использовать его в дальнейшем

var el = $('<div class="row moving"><div class="col-md-12"><span class="steps">Step</span><span><textarea class="form-control" rows="3" cols="105"></textarea></span><span class="glyphicon glyphicon-circle-arrow-up"></span><span class="glyphicon glyphicon-circle-arrow-down"></span><span class="step_remove">X</span></div></div>'); 
$('.makeit_steps').append(el); 

После добавления нового элемента необходимости чтобы назначить событие нажмите на стрелки вверх и вниз для того, вы должны сделать этот путь

для стрелка вверх,

$('.glyphicon glyphicon-circle-arrow-up',el).on('click',function(){ 

для стрелка вниз

$('.glyphicon-circle-arrow-down',el).on('click',function(){ 

вы можете увидеть объект e1, используемый при применении события click. Вышеуказанные строки будут искать стрелки вверх и вниз только в добавленном новом элементе и назначат событие.

рабочая демо здесь - http://jsfiddle.net/m86p420h/7/

+0

все еще получаю глюк в вашем демо время замены '' step' и heading' – Raviteja

+0

, что именно вы подразумеваете под глюк, пожалуйста, объясните подробно, что поможет решая вопрос. Также некоторые конкретные сценарии, когда это происходит – nshah143

+0

Привет @Raviteja, вы можете проверить обновление FIddle здесь сейчас - http://jsfiddle.net/m86p420h/10/. Если какой-либо вопрос все еще существует, объясните, что и когда оно происходит. – nshah143