2016-09-20 4 views
1

У меня есть 3 кнопки, центрированные в контейнере. Когда пользователь нажимает на одну из них, кнопка должна идти в левую верхнюю часть контейнера. Другие кнопки должны исчезнуть.анимировать из центра влево с помощью jquery

Мне это удалось, но я не могу заставить кнопку запускать анимацию из исходной позиции, потому что я меняю положение кнопки на абсолютное, прежде чем запускать анимацию.

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

Вот мой HTML:

<body> 
    <div id="inner_body" style="position:relative;margin: auto;text-align: center;width:50%;margin-top: 200px"> 
     <button class="bc" id="0" style="margin-top: 400px;margin-left:20px;margin-right:20px;padding: 20px;background-color: #718bf3">Botton A</button> 
     <button class="bc" id="1" style="margin-top: 400px;margin-left:20px;margin-right:20px;padding: 20px;background-color: #718bf3">Botton B</button> 
     <button class="bc" id="2" style="margin-top: 400px;margin-left:20px;margin-right:20px;padding: 20px;background-color: #718bf3">Botton C</button> 
    </div> 
</body> 

И Jquery скрипт:

$(document).on('click', '.bc', function() { 
    $('#' + this.id + '').css({ 
     position: 'absolute' 
    }).animate({ 
     left: 0, 
     marginTop: 0 
    }, "slow"); 
    for (var i = 0; i < 3; i = i + 1) { 
     if (i != this.id) { 
      $('#' + i + '').delay(1200).fadeOut(300); 
     } 
    } 
}); 
+0

Параметр 'inner_body' закрепил' height'? –

+0

№. Внутренняя высота тела динамическая. После нажатия кнопки будет заполнено больше текста. – Andy

ответ

0

Получить начальное положение элемента с помощью 'position' и повторно использовать его перед началом анимации.

var x=$(this).position().left; 
var y=$(this).position().top; 
$(this).css({'position': 'absolute','top': y+'px','left': x+'px'}) 
+0

ОК, это работает - сначала я установил его для всех 3 кнопок, а затем активировал анимацию! – Andy

0

Я просто обновлен для работы с автоматической высоты #inner_body (jsfiddle обновленный слишком)

HTML

<div id="inner_body"> 
    <button>Botton A</button> 
    <button>Botton B</button> 
    <button>Botton C</button> 
</div> 

CSS

#inner_body { 
    position: relative; 
    margin: auto; 
    text-align: center; 
    width: 50%; 
    height: auto; 
    border: 1px solid #000; 
} 

button { 
    position: absolute; 
    bottom: 0; 
    padding: 20px; 
    background-color: #718bf3; 
} 

button:nth-child(1) { 
    left: 40px; 
} 

button:nth-child(2) { 
    left: 170px; 
} 

button:nth-child(3) { 
    left: 300px; 
} 

JS

$(document).on('click', 'button', function() { 
    $(this).animate({ 
     left: 0, 
     top: 0, 
    }, "slow").css('bottom', 'auto'); 
    $(this).siblings().delay(1200).fadeOut(300); 
}); 

jsfiddle

0

Вот моя попытка с помощью CSS transition собственности https://jsfiddle.net/abkow4zt/1/

$(document).on('click', '.bc', function() { 
 
\t \t 
 
\t \t $(this).css({'top': $(this).position().top + 'px','left': $(this).position().left + 'px'}); // set origin position 
 
    \t $(this).addClass('onclick'); // add class with transition to clicked button 
 
\t 
 
    setTimeout(function() { 
 
     $('button.bc').each(function() { 
 
     if(!$(this).hasClass('onclick')) $(this).fadeOut(300); // smoth hide other buttons 
 
     }, 1200); // after 1200ms deylay 
 
    }); 
 

 
}); \t
#inner_body { 
 
    position:relative; 
 
    margin: auto; 
 
    text-align: center; 
 
    margin-top: 50px 
 
    border: 1px solid grey; 
 
} 
 

 
button { 
 
    margin-top: 400px; 
 
    margin-left:20px; 
 
    margin-right:20px; 
 
    padding: 20px; 
 
    background-color: #718bf3; 
 
    transition: transform 1s, -webkit-transform 1s, -ms-transform 1s; 
 
} 
 

 
.onclick { 
 
    position: absolute; 
 
    -ms-transform: translate(-20px, -400px); 
 
    -webkit-transform: translate(-20px, -400px); 
 
    transform: translate(-20px, -400px); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="inner_body"> 
 
    <button class="bc" id="0">Botton A</button> 
 
    <button class="bc" id="1">Botton B</button> 
 
    <button class="bc" id="2">Botton C</button> 
 
</div>