Roe*_*oel 3 javascript css jquery jquery-animate
我有一个属性为"Position:relative;"的DIV.现在,这些DIV中有三个.他们都获得了一个独特的ID等.
现在,如果我单击DIV,我希望它能够动画到文档中的某个位置.虽然我无法确定左/上值,因为如果我使用"top"和"left",它会相对地将左侧设置为其父项位置.
也许有点不清楚,但这是我得到的.
将移动的可点击DIV的CSS.
div#left_hldr .switch_project {
z-index: 1001;
position: relative;
margin: 10px 0px 0px 0px;
cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)
现在,我现在得到的jQuery代码.
// Open project.
$(".switch_project").live('click', function() {
// Get the ID value.
var More_Id = $(this).attr("id");
// Explode the Id.
var Id_Split = More_Id.split("_");
// Get the project ID.
var Project_Id = Id_Split[2];
/*
Replacement of the switch project div.
1 ) Define the current position.
2 ) Define the new position.
3 ) Replace the DIV to the new position.
4 ) Fade the new page in.
5 ) Put the DIV back to its original position.
*/
// Current Position.
var Ori_Left = $(this).offset().left;
var Ori_Top = $(this).offset().top;
// New Position. [ Based on the content_hldr container ]
var New_Top = $("div#content_hldr").offset().top;
var New_Left = $("div#content_hldr").offset().left;
// Define the current div.
var Div_Rep = $(this);
// Hide the More Info tab.
$(Div_Rep).children(".more_info").fadeOut("fast");
// Fade content out.
$("div#content_hldr").fadeOut("fast");
// Replace the div.
$(Div_Rep).animate({
top: New_Top,
left: New_Left
}, "slow", function() {
// Load Home page in.
$("div#content_hldr").load("content/content.projects.php?id=" + Project_Id, function() {
// Re-define Cufon.
Cufon.replace('h2');
});
// Fade in the content.
$("div#content_hldr").fadeIn("fast", function() {
// Hide the replaced div.
$(Div_Rep).hide();
// Replace it back to its position.
$(Div_Rep).css({
top: Ori_Top,
left: Ori_Left
});
// Show the More Info tab again.
$(Div_Rep).children(".more_info").show();
// Fade back in.
$(Div_Rep).fadeIn("medium");
});
});
});
Run Code Online (Sandbox Code Playgroud)
......它会将左边相对设置为父母的位置.
实际上,没有.如果你使用left和top使用一个position: relative元素,它们会将它从未定位的位置(例如,在静态流中)偏移,同时继续在静态流中保留其空间.一个微妙但重要的区别(对于拖放非常有用).
如果你想以动画到文档的左上角,你可以计算出它的(通过偏移offset),然后提供这些为负数left和top,因为当然,如果是在(说)[100,50],然后将其定位在[-100,-50]与其默认位置相比将......置于[0,0].
像这样:
$("selector_for_your_divs").click(function() {
var pos, $this;
$this = $(this);
pos = $this.offset();
$this.animate({
left: "-" + pos.left + "px",
top: "-" + pos.top + "px"
});
});
Run Code Online (Sandbox Code Playgroud)
类似地,如果你想将它移动到另一个元素所在的位置,只需从其他元素的位置减去它的位置 - 这将为你提供应用的增量:
$("selector_for_your_divs").click(function() {
var mypos, otherpos, $this;
// Move to the target element
$this = $(this);
pos = $this.offset();
otherpos = $('selector_for_other_element').offset();
pos.left = otherpos.left - pos.left;
pos.top = otherpos.top - pos.top;
$this.animate({
left: pos.left + "px",
top: pos.top + "px"
});
});
Run Code Online (Sandbox Code Playgroud)