标题部分视差滚动效果jQuery和垂直中心边距

时间:2014-08-19 21:58:03

标签: jquery html css margin parallax

我有一个带有背景图片的标题部分和一个带有徽标的元素 现在这个标志在该部分的中间以jQuery为中心 当我尝试为徽标添加视差效果时,它不再居中,因为我也使用了视差的边距变化。

这是我的代码我还添加了一个JS Fiddle Link(视差效果在编辑器iframe中不起作用,所以你必须在新窗口中打开这个例子。

JS Fiddle Editor
JS Fiddle Show

代码:

// Viewport Height for head section
function viewport_height() {
    var height = $(window).height();
    var viewportHeight = (50 * height) / 100;
    var viewportHeightInner = (50 * height) / 150;
    var viewportHeightInnerMargin = (50 * height) / 300;
    viewportHeight = parseInt(viewportHeight) + 'px';
    viewportHeightInnerMargin = parseInt('-' + viewportHeightInnerMargin) + 'px';
    $(".head").css('height',viewportHeight);
    $(".head .background").css('height',viewportHeight);
    $(".head .inner").css('height',viewportHeightInner);
    $(".head .inner").css('width',viewportHeightInner);
    $(".head .inner").css('margin-top',viewportHeightInnerMargin);
    $(".head .inner").css('margin-left',viewportHeightInnerMargin);
}

// Resize head section on scale
$(document).ready(function() {
    viewport_height();
    $(window).bind('resize', viewport_height);
});

// Logo Parallax scroll
$(window).scroll(function(e){
    if ($(window).width() > 800) {
        $('.head .inner').css({
            'margin-top' : +($(this).scrollTop()/2)+"px",
        });
    }
});

1 个答案:

答案 0 :(得分:1)

不要将带有负边距的绿框居中,而是尝试使用此居中方法:

section.head .inner {
  position: relative;
  top: 50%;
  left: 50%;
  background-color: green;
  -webkit-transform:translate(-50%, -50%);
  -moz-transform:translate(-50%, -50%);
  -ms-transform:translate(-50%, -50%);
  -o-transform:translate(-50%, -50%);
  transform:translate(-50%, -50%);
}

您必须编辑JS以删除负边距。只需删除这些行:

$(".head .inner").css('margin-top',viewportHeightInnerMargin);
$(".head .inner").css('margin-left',viewportHeightInnerMargin);
相关问题