javascript - JQuery 动画 margin-top 使用 var 不工作

标签 javascript jquery html css jquery-animate

我正在使用 JQuery 让我的 .wrapper div 在移动到 margin-top 之后快速恢复到它原来的 margin-top。原始边距顶部取决于浏览器高度。我试图通过将原始 margin-top 值存储到一个变量中,并在我想要 .wrapper div 稍后恢复时将它用于 JQuery 动画来实现这一点。

$(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 不接受我的变量(存储原始 margin-top 值的地方),即使转换为字符串?我不想使用静态值作为我的 margin 顶部。

如果您想查看应用程序代码,请点击此处。 http://codepen.io/myleschuahiock/pen/zqvvNZ

感谢任何帮助!谢谢!

EDIT: I changed the click function to $('.go-back'), but the animate for magin-top should still be the same

最佳答案

将整个 $(".title").click(function(){}) 移动到 $(document).ready(function(){})

问题存在是因为在 $(".title").click(function(){}) 初始化时 originalMargin 尚未设置因为文档还没有就绪

关于javascript - JQuery 动画 margin-top 使用 var 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822900/

相关文章:

javascript - 如何禁用 IE 中图像的图像工具栏?

javascript - 如何在点击jquery时平滑滚动

javascript - Titanium ScrollView 不会从左向右滚动

jquery - 在 BaguetteBox 中的每个图像下方添加按钮

javascript - Chrome HTML5 视频缓冲

javascript - ReactJS :Syntax error: src/App. js:意外 token (16:6)

javascript - 使用 JavaScript 变量作为 jQuery 选择器的问题——无法识别的表达式

jquery - 哪种 jQuery 选择效率更高?

html - Webpack 3.9.1 - 如何将 LESS 文件合并到一个 CSS 文件中?

html - CSS:不等边三 Angular 形伪元素上的盒阴影效果