Я спросил, есть ли в любом случае, чтобы получить старую позицию из div в моем случае. .tile
перемещается в левый угол, когда его щелкают. когда я нажимаю кнопку закрытия, он должен вернуться в положение OLD.
Вот JSFiddle
$(".tile").on("click", function (e) {
var pos = $(this).position();
e.stopPropagation();
if(!$(this).hasClass('open') ) {
$(this).animate({
"top": pos.top - pos.top,
"left":pos.left - pos.left,
"width": "100%",
"height": "100%"
}, 1000).addClass('open');
}
});
$(".close").on("click", function (e) {
e.stopPropagation();
$(this).parent().stop().animate({
// here i need the old position
"width": "100px",
"height": "50px"
}, 1000).removeClass('open');
});
CSS
.tile {
position: absolute;
background-color:#0090db;
}
#tp1{
width: 100px;
height: 50px;
}
.close {
display: none;
background-color:#C85051;
position: absolute;
top: 0;
right: 5px;
width: 50px;
height: 25px;
text-align: center;
}
.open .close {
display: block;
}
HTML
<div class="tile" id="tp1">
<img class="bus" src="http://s14.directupload.net/images/131130/4gzq9oaz.png" />
<div class="close">x</div>
</div>
Поскольку вы позиционируете свои элементы с position:absolute
один параметр создает два var
которые сохраняют первую позицию значения:
var posL , posT;
А затем присвойте значения функции click
следующим образом:
var posL = $(this).css('left'),
posT = $(this).css('top');
Просмотрите эту демонстрацию http://jsfiddle.net/2Zx3m/10/
редактировать
Чтобы заботиться о global var
переменном, как пользователь gaynorvader, вы можете вызвать весь свой код в функцию анонимного типа:
(function(){
/* code */
}())
О причине заботы о global var
вы можете увидеть здесь и здесь
Кроме того, вы можете больше узнать о функции с немедленным вызовом
Вы можете сохранить позицию элемента, используя данные jQuery.
Дополнительная информация здесь: http://api.jquery.com/jQuery.data/
$(".tile").on("click", function (e) { //opens the login
var pos = $(this).position();
e.stopPropagation();
if(!$(this).hasClass('open') ) {
$(this).animate({
"top": pos.top - pos.top,
"left":pos.left - pos.left,
"width": "100%",
"height": "100%"
}, 1000).addClass('open');
$(this).data('pos', pos); // Save the position here
}
});
$(".close").on("click", function (e) {
e.stopPropagation();
var elem = $(this).parent();
var pos = elem.data('pos'); // Retrieve the position
elem.stop().animate({
"top": pos.top,
"left": pos.left,
"width": "100px",
"height": "50px"
}, 1000).removeClass('open');
});
Используйте margin-left
. Положите его отрицательно на положение элемента, а затем верните его обратно на 0: http://jsfiddle.net/2Zx3m/12/
$(this).animate({
"top": pos.top - pos.top,
//"left":pos.left - pos.left,
"margin-left": - pos.left,
"width": "100%",
"height": "100%"
}, 1000).addClass('open');
И назад:
$(this).parent().stop().animate({
// here i need the old position
"margin-left": 0,
"width": "100px",
"height": "50px"
}, 1000).removeClass('open');
Получите старую позицию... нет. Помните старую позицию... конечно. Просто сохраните текущую позицию перед перемещением.
Вот как бы я поступил так с минимальным кодом и разочарованием.
Я использую jQuery toggleClass
чтобы полагаться в основном на CSS для своей позиции.
HTML:
<div class="car left">
<img src="http://s14.directupload.net/images/131130/4gzq9oaz.png" alt="bus" class="minBus" />
<span class="close">X</span>
</div>
<div class="car right">
<img src="http://s14.directupload.net/images/131130/4gzq9oaz.png" alt="bus" class="minBus" />
<span class="close">X</span>
</div>
CSS:
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.car {
background: lightBlue;
width: 160px;
height: 70px;
float: left;
position: absolute;
transition: all 1s ease;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-ms-transition: all 1s ease;
-o-transition: all 1s ease;
}
.car.active {
width: 100%;
height: 100%;
left: 0;
z-index: 10;
}
.right {
left: 400px;
}
.minBus {
width: 140px;
height: 56px;
transition: all 1s ease;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-ms-transition: all 1s ease;
-o-transition: all 1s ease;
}
.minBus.active {
width: 100%;
height: 100%;
}
.close {
display: none;
position: absolute;
right: 0;
top: 0;
background: brown;
width: 40px;
height: 40px;
text-align: center;
line-height: 40px;
}
.close.active {
display: block;
}
Немного о jQuery:
function toggle() {
$('.car').on('click', function() {
$(this).toggleClass('active').find('.minBus, .close').toggleClass('active');
});
}
toggle();
Это использует стили для переключения между ними, поэтому нет необходимости в вычислениях.
Вот JSFiddle.
Самое замечательное в этом то, что jQuery не использует множество inline-styles
. Вместо .animate
мы переключаем классы, которые содержат все стили внутри них.