纯javascript中的平滑垂直选项卡式导航

时间:2014-10-11 11:40:10

标签: javascript html css dom navigation

我想要一个平滑的过渡垂直选项卡式导航,例如this和纯js解决方案。

我尝试了一些东西,但它没有那么顺利,也没有将内容滚动到div的顶部。

Lorem ipsum dolor坐在amet,consectetur adipisicing elit。错误丘比特veritatis laudantium possimus quia nulla ut accusantium,dolores consectetur tempora officiis nemo similique voluptates nostrum architecto,quas qui iste sapiente。
<div class="wrapper">

        <div id="left">
                <a class="links_" href="#one_">tab 1</a>
                <a class="links_" href="#two_">tab 2</a>
                <a class="links_" href="#three_">tab 3</a>
                <a class="links_" href="#four_">tab 4</a>
                <a class="links_" href="#five_">tab 5</a>
        </div>
        <div id="main" class="main">
            <div class="ctr" id="one_">1. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate tenetur earum voluptate iste maxime in quod deleniti, omnis ipsam corporis atque veritatis facilis fugiat quisquam? Illum odit ratione, recusandae doloremque.</div>
            <div class="ctr" id="two_">2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div><div class="ctr" id="three_">3. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div><div class="ctr" id="four_">4. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div><div class="ctr" id="five_">5. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div>
        </div>
    </div>

    <script>
    (function() {

            var d = document;
            var getId = function(id) { return d.getElementById(id); };
            var getClass = function(cl) { return d.getElementsByClassName(cl); };

            var link_ = getId("left"), first_ = getId("first"), main_ = getClass('ctr'), mid_= getId("main"), a = document.getElementsByTagName("a");
                // console.log(a);
                for(var i=0; i<=a.length;i++){
                console.log(a[i]);
                a.onclick = function(){
                    var href = this.getAttribute("href");
                    href = href.replace("#","");
                    d.getId(href).scrollTop = mid_.offsetTop+first_.offsetHeight;

                };

                }
                })();


    </script>

它将整个页面放到顶部,因为我使用的超链接可能是。任何解决方案?

Fiddle Demo

1 个答案:

答案 0 :(得分:-1)

&#13;
&#13;
(function() {
  // addEvent wraper for crossbroswer 
  // you can use this as addEvent(element,"click"||"mouseover"||"mouseout",callbackfunction);
  if (typeof addEventListener !== "undefined") {
    addEvent = function(obj, evt, fn) {
      obj.addEventListener(evt, fn, false);
    };

    removeEvent = function(obj, evt, fn) {
      obj.removeEventListener(evt, fn, false);
    };
  } else if (typeof attachEvent !== "undefined") {
    addEvent = function(obj, evt, fn) {
      var fnHash = "e_" + evt + fn;

      obj[fnHash] = function() {
        var type = event.type,
          relatedTarget = null;

        if (type === "mouseover" || type === "mouseout") {
          relatedTarget = (type === "mouseover") ? event.fromElement : event.toElement;
        }

        fn.call(obj, {
          target: event.srcElement,
          type: type,
          relatedTarget: relatedTarget,
          _event: event,
          preventDefault: function() {
            this._event.returnValue = false;
          },
          stopPropagation: function() {
            this._event.cancelBubble = true;
          }
        });
      };

      obj.attachEvent("on" + evt, obj[fnHash]);
    };
  }

  // this is magical animateScroll function which take first paramter as a document element
  // second parameter as time in milisecond 
  // third as a callbackfunction when animation is completed
  function animateScroll(elem, time, callbackfunction) {
    if (!elem) return;
    var to = elem.offsetTop;
    var from = window.scrollY;
    var start = new Date().getTime(),
      timer = setInterval(function() {
        var step = Math.min(1, (new Date().getTime() - start) / time);
        window.scrollTo(0, (from + step * (to - from)) + 1);
        if (step == 1) {
          clearInterval(timer);
          callbackfunction();
        };
      }, 25);
    window.scrollTo(0, (from + 1));
  }

  var d = document;
  var getId = function(id) {
    return d.getElementById(id);
  };
  var getClass = function(cl) {
    return d.getElementsByClassName(cl);
  };
  //temp array will use this to change URL and document element from the DOM
  var ar = ["one_", "two_", "three_", "four_", "five_"];
  var link_ = getId("left"),
    first_ = getId("first"),
    main_ = getClass('ctr'),
    mid_ = getId("main"),
    a = d.getElementsByTagName("a");
  for (var i = 0; i < a.length; i++) {
    a[i].val = i;
    //adding the OnClick function to various a Tags
    addEvent(a[i], "click", (function() {
      var element = getId(ar[this.val]);

      function callBackFun(ele) {
        var strChangeHref = ar[ele];
        //change the hash URL value
        window.location.hash = strChangeHref;
      };
      var getLastVal = this.val;
      var returnVal = function() {
        callBackFun(getLastVal);
      };
      animateScroll(element, 300, returnVal);
    }), true);
  }
})();
&#13;
#left {
  position: fixed;
  left: 0;
  top: 60px;
}
#left .links_ {
  padding: 30px 10px;
  border: 1px solid #eee;
  color: #888;
  font-size: 1.2em;
  text-transform: uppercase;
  display: block;
}
.main .ctr {
  width: 400px;
  height: 400px;
  margin-left: 100px;
  border: 1px solid #eee;
  padding: 20px
}
/*.main div{display: none;}*/

.main .ctr.shown {
  display: block;
}
&#13;
<div id="first">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error cupiditate veritatis laudantium possimus quia nulla ut accusantium, dolores consectetur tempora officiis nemo similique voluptates nostrum architecto, quas qui iste sapiente.</div>
<div class="wrapper">

  <div id="left">
    <a class="links_" href="javascript:;">tab 1</a>
    <a class="links_" href="javascript:;">tab 2</a>
    <a class="links_" href="javascript:;">tab 3</a>
    <a class="links_" href="javascript:;">tab 4</a>
    <a class="links_" href="javascript:;">tab 5</a>
  </div>
  <div id="main" class="main">
    <div class="ctr" id="one_">1. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate tenetur earum voluptate iste maxime in quod deleniti, omnis ipsam corporis atque veritatis facilis fugiat quisquam? Illum odit ratione, recusandae doloremque.</div>
    <div class="ctr" id="two_">2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div>
    <div class="ctr" id="three_">3. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div>
    <div class="ctr" id="four_">4. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div>
    <div class="ctr" id="five_">5. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit reprehenderit, eveniet pariatur tempora deserunt nobis, asperiores odio quasi dolorem. Eius soluta ullam atque nesciunt numquam enim, vitae recusandae animi aliquid!</div>
  </div>
</div>
&#13;
&#13;
&#13;

编辑: 添加了一个回调函数来更改URL Fiddle Demo