简体   繁体   English

页眉节视差滚动效果jQuery和垂直中心边距

[英]Header Section Parallax Scroll Effect jQuery And Vertical Center Margin

I have a header section with a background image and a element inside with a logo. 我有一个带有背景图片的标头部分,一个带有徽标的元素。
Now this logo is centered with jQuery in the middle of the section. 现在,此徽标以jQuery居中。
When I try to add a parallax effect to the logo it's not centered anymore because I use also a margin change for the parallax. 当我尝试向徽标添加视差效果时,它不再居中,因为我还对视差使用了边距更改。

This is my code I also added a JS Fiddle Link ( the parallax effect is not working in the editor iframe so you have to open the example in a new window. 这是我的代码,我还添加了JS Fiddle Link(视差效果在iframe编辑器中不起作用,因此您必须在新窗口中打开示例。

JS Fiddle Editor JS小提琴编辑器
JS Fiddle Show JS小提琴秀

Code: 码:

// 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",
        });
    }
});

Rather than centering the green box with negative margins, try this centering method instead: 而不是使用负边距将绿色框居中,请尝试使用以下居中方法:

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%);
}

You'll have to edit the JS to remove the negative margins. 您必须编辑JS才能删除负边距。 Just remove these lines: 只需删除这些行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM