2016-03-06 37 views
0

我使用jQuery让我的.wrapper div在移动到margin-top后回到原来的margin-top。原始页边距取决于浏览器高度。我试图通过将原始margin-top值存储到一个变量中,并在我想让.wrapper div稍后回滚时将它用于JQuery动画。JQuery的动画边缘顶部使用var不工作

$(document).ready(function() { 
//Adjust .wrapper Margin-top to adjust position to 1/4 of Window Broswer Height 
var marginWindowSpace = ($(window).height())/4; 
$(".wrapper").css("margin-top", marginWindowSpace); 

var originalMargin = $(".wrapper").css("margin-top").toString(); 
}); 

$(".title").click(function() { 
    $("#results-container").empty(); 
    $(".wrapper").animate({ 
    'margin-top': originalMargin 
    }, 200); 
    $(".title-tag, .or, .random-article, .random-article-underline").fadeIn(500); 
    $("footer").addClass("footer-pos1"); 
}); 

问题:为什么不会我有生的margin-top接受我的变量(其中原边距值存储),甚至当转换成字符串?我不想使用静态值作为我的保证金。

如果您想查看应用程序代码,它就在这里。 http://codepen.io/myleschuahiock/pen/zqvvNZ

任何帮助表示赞赏!谢谢!

编辑:我改变了点击功能$,但magin顶的动画应该还是一样

回答

1

移动整个$(".title").click(function(){})到(“去背。”)存在$(document).ready(function(){})

的问题,因为在该$(".title").click(function(){})originalMargin初始化的时候并没有被设定,因为document不是ready尚未。

0

这样做。你的动画部分有一些错误。 margin-top应该是正确的marginTop和你的字符串应该转换为int并且像这样做。我将以example.hope的形式实现,这将对您有所帮助。

<!DOCTYPE html> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
 
<head> 
 
<title>Test</title> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
 
</head> 
 
<style type="text/css"> 
 
body{ 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
div.testing{ 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: orange; 
 
    margin-top: 100px; 
 
} 
 

 
div.two{ 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: green; 
 
    position: 
 
} 
 

 
</style> 
 
<body> 
 

 
<div class="testing"></div> 
 
<br><br> 
 
<h3 class="clk">Click me!</h3> 
 
<div class="two"></div> 
 

 
<script type="text/javascript"> 
 
$(document).ready(function(){ 
 
    var one = $(".testing").css("margin-top").toString(); 
 
    var vaL = parseInt(one,10); 
 

 
    $(".clk").click(function(){ 
 
    $(".two").animate({'marginTop':vaL+'px'},1000); 
 
    }); 
 
}); 
 

 
</script> 
 

 

 
</body> 
 
</html>

注:

var one = $(".testing").css("margin-top").toString(); 

INT这部分得到margin-top值作为一个字符串。

var vaL = parseInt(one,10); 

将其转换为整数。

那么动画部分

$(".two").animate({'marginTop':vaL+'px'},1000);