简体   繁体   中英

show hidden div and smoothly scroll to anchor point within hidden div

I have many hidden divs (within the normal site layout) which I make shown only one at a time and in all cases the screen scrolls to those specific divs. This code works nicely but I want it to open the hidden div and scroll to the anchor within that div .

I can't seem to ingrate something that does it all. In this case it will only arrive at the top of the hidden div.

var holder = "";

function toggleDiv(id) {

  if (holder != "") {
    document.getElementById(holder).style.display = 'none';
  }

  document.getElementById(id).style.display = 'block';
  holder = id;

  var startY = currentYPosition();
  var stopY = elmYPosition(id);
  var distance = stopY > startY ? stopY - startY : startY - stopY;
  if (distance < 100) {
    scrollTo(0, stopY);
    return;
  }
  var speed = Math.round(distance / 100);
  if (speed >= 10) speed = 10;
  var step = Math.round(distance / 25);
  var leapY = stopY > startY ? startY + step : startY - step;
  var timer = 0;
  if (stopY > startY) {
    for (var i = startY; i < stopY; i += step) {
      setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
      leapY += step;
      if (leapY > stopY) leapY = stopY;
      timer++;
    }
    return;
  }
  for (var i = startY; i > stopY; i -= step) {
    setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
    leapY -= step;
    if (leapY < stopY) leapY = stopY;
    timer++;
  }

  return false;

}

I also have this to make the whole scroll thing work:

function currentYPosition() {
  // Firefox, Chrome, Opera, Safari
  if (self.pageYOffset) return self.pageYOffset;
  // Internet Explorer 6 - standards mode
  if (document.documentElement && document.documentElement.scrollTop)
    return document.documentElement.scrollTop;
  // Internet Explorer 6, 7 and 8
  if (document.body.scrollTop) return document.body.scrollTop;
  return 0;
}

function elmYPosition(id) {
  var elm = document.getElementById(id);
  var y = elm.offsetTop;
  var node = elm;
  while (node.offsetParent && node.offsetParent != document.body) {
    node = node.offsetParent;
    y += node.offsetTop;
  }
  return y;
}

So, what I would really like is to know if there is any command I can introduce in there to allow it to scroll smoothly/nicely to anchors instead of just jumping to them. Thanks in advance.

You can animate the scroll:

$('html,body').animate({

    scrollTop: $('#yourTarget').offset().top

 }, 2000);

Also, you can't scroll to the hidden div, because display:none removes it from the DOM, when you should actually be using visibility:hidden , so you can still use the anchor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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