简体   繁体   English

如果元素在data-attribute上滚动,则

[英]If element is scrolled on data-attribute then

I have two headers (menu1 - default, menu2 - display:none). 我有两个标题(菜单1-默认值,菜单2-显示:无)。

In sections of website I added special attribute (data-ix="change-header"). 在网站的各个部分中,我添加了特殊属性(data-ix =“ change-header”)。 I want to have the effect.. that if I will scroll site and if we scrolled on section where data-ix="change-header" then header will be other - so menu1 will be display:none and menu2 will be display:block; 我想产生效果..如果我要滚动站点,并且如果我们滚动到data-ix =“ change-header”的部分,则标题将是其他-因此menu1将显示:none,menu2将显示:block ;

I have something like that, but I don't know how I can use scroll. 我有类似的东西,但我不知道如何使用滚动。

if ($(this).attr("data-ix") == "change-header"){
    $("‪#‎menu1‬").css("display","none");
    $("‪#‎menu2‬").css("display","block");
} else {
    $("#menu1").css("display","block");
    $("#menu2").css("display","none");
}

My html looks like that: 我的html看起来像这样:

<header id="menu1"></header>
<header id="menu2"></header>
<div class="test" data-ix="change-header"></div>
<div class="test"></div>
<div class="test" data-ix="change-header"></div>
<div class="test" data-ix="change-header"></div>
<div class="test" data-ix="change-header"></div>
<div class="test"></div>
<footer></footer>

Help :) 救命 :)

You can take a look at this: http://janpaepke.github.io/ScrollMagic/ 您可以看一下: http : //janpaepke.github.io/ScrollMagic/

It's only 6Kb gzipped, and it lets you animate elements or toggle CSS classes based on scroll position :) 压缩后只有6Kb,它可以使元素动起来或根据滚动位置切换CSS类:)

You can compute the threshold values at which you will change header (or not). 您可以计算更改标头(或不更改标头)的阈值。 Something like this 像这样

var thresholds = [];
$('.test').each(function(i, e) {
  // after we scroll past the top coordinate of this element,
  // either show or hide the second header, based on the presence
  // of the data-ix attribute
  thresholds.push([e.offsetTop, $(e).data('ix') === 'change-header']);
});

Then, consult these thresholds on every scroll event 然后,在每个滚动事件中查阅这些阈值

// cache menu elements
var $menu1 = $('#menu1'), $menu2 = $('#menu2');

// update header once, and listen on scroll
update();
$(window).on('scroll', update);

function update() {
  // pick first visible threshold
  var scrollTop = $(this).scrollTop(), thresh;
  for (var i = 0, len = thresholds.length; i < len; ++i) {
    thresh = thresholds[i];
    if (thresh[0] >= scrollTop) break;
  }

  // update header as necessary
  if (thresh[1]) {
    $menu1.hide();
    $menu2.show();
  } else {
    $menu2.hide();
    $menu1.show();
  }
}

Here is a working Plunker. 是一个正在工作的柱塞。

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

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