【问题标题】:horizontal scroll when clicking on the navbar links单击导航栏链接时水平滚动
【发布时间】:2020-09-14 10:48:58
【问题描述】:

我刚开始编码,我在某个地方遇到了问题,我的javascript知识很少,可能太容易了,我做不到。我正在尝试建立一个水平滚动的网站。我已经用按钮完成了转换,但是我想用导航栏中的链接进行转换当我点击导航链接时,我想去其他部分。我该怎么做?

HTML 代码

 <div class="navbar">
        <a href="" class="logo">
            <img src="" alt="" class="logo-img">
        </a>
        <nav class="nav-list">
            <a href="#home" class="nav-link home-btn">HOME</a>
            <a href="#about" class="nav-link about-btn">ABOUT</a>
            <a href="#portfolio" class="nav-link port-btn">PORTFOLIO</a>
        </nav>
    </div>

    <button class="page-btn left-btn">
        <i class="fa fa-arrow-left" aria-hidden="true"></i>
    </button>
    <button class="page-btn right-btn">
        <i class="fa fa-arrow-right" aria-hidden="true"></i>
    </button>

 
        <section class="section-1" id="home">
                <div class="section-title">
                    <h1 class="section-1-hd">
                        SECTION ONE
                    </h1>
                </div>
        </section>
        <section class="section-2" id="about">
                <div class="section-title">
                    <h1 class="section-2-hd">
                        SECTION TWO
                    </h1>
                </div>
        </section>
        <section class="section-3" id="portfolio">
                <div class="section-title">
                    <h1 class="section-3-hd">
                        SECTION THREE
                    </h1>
                </div>
        </section>

Javascript 代码

var counter1 = 0;
var counter2 = 1;


const sections = document.querySelectorAll('section');

  if(counter1 === 3) {
    Array.from(sections).forEach(section =>{
      section.style.left = "0"
    })
    counter1=0;
    counter2=1;
   
}

  if(counter1 === -1) {
    Array.from(sections).forEach(section =>{
      if(section.classList[0] === 'section-3') {
        return;
      }
      section.style.left ='-100vw'
    })
    counter1=2;
    counter2=3;
   

  };

window.addEventListener('wheel' , (e) =>{
  const deltaY = e.deltaY > 0;

  if(deltaY) {
    counter1++;
    counter2++;
  }else {
    counter1--;
    counter2--;
  }

  console.log(counter1,counter2);

  document.querySelector(`.section-${deltaY ? counter1 : counter2}`).style.left = `${deltaY ? "-100vw" : "0"}`;
  });


  document.querySelector('.left-btn').addEventListener('click' , () => {
    counter1--;
    counter2--;
   document.querySelector(`.section-${counter2}`).style.left = '0';
  });

  document.querySelector('.right-btn').addEventListener('click' , () => {
    counter1++;
    counter2++;
    document.querySelector(`.section-${counter1}`).style.left = '-100vw';
  });


我可能写了一个非常糟糕的代码,我为此道歉。

【问题讨论】:

    标签: javascript html navigation horizontal-scrolling


    【解决方案1】:

    首先,我们将所有部分元素存储到一个数组中

    const sections = document.querySelectorAll('section');
    

    然后,创建一个函数,该函数将导航或设置当前滚动 x 位置到下一个或上一个部分。

    let index = 0;
    function navigate(direction) {
      if (direction === 'next') {
        index = ++index % sections.length;
      }
      if (direction === 'prev') {
        index = (index > 0) ? --index : index;
      }
    
      window.scrollTo(sections[index].getBoundingClientRect().left, 0);
    }
    

    此函数会将当前节索引增加 1 并将其模数为节数组的大小,如果大于 0,则减 1。

    得到新的section索引后,我们使用window.scrollTo(x, y)导航到目标section的left属性。

    现在,我们完成了 javascript,让我们回到 HTML。而不是使用eventListener,像这样使用onclick更容易

    <button class="page-btn left-btn" onclick="navigate('prev')">
      prev
      <i class="fa fa-arrow-left" aria-hidden="true"></i>
    </button>
    <button class="page-btn right-btn" onclick="navigate('next')">
      next
    <i class="fa fa-arrow-right" aria-hidden="true"></i>
    </button>
    

    onclick 中,我们传入navigate 函数,其参数为'next' 或'prev'

    你有它!

    编辑:对于这一行

    index = (index > 0) ? --index : index;
    

    这等价于这个

    if (index > 0) {
        --index;
    }
    

    【讨论】:

    • 非常感谢您抽出宝贵时间回答我的问题。我无法将您编写的代码集成到我的代码中,因为我的 js 经验很少,但我创建了一个 codepen 项目,如果您可以检查一下。我想在点击Home时切换到Section 1,当我点击About时切换到Section 2,当我点击Portfolio codepen.io/ibrahimgedik/pen/ZEWRvYV你可以查看我的css代码,因为我把所有的页面都叠加了z索引。 再次感谢您
    【解决方案2】:

    如果您愿意使用 jquery,我可以从我自己的工具箱中为您提供一个功能。给定一个周围的容器,您的导航项是您要滚动到的子元素。

    包括jquery(2020/14/09有效):

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    

    有一个javascript函数来做滚动。像这样,使用.animate(..):

    /** Will center the scroll-bar of a container onto one of his child elements horizontally.
     * @param id_container: id string of the scrollable container.
     * @param id_target   : id string of the target that is to be centered to.
     *   Should be a child of above container.
     * @param additional_offset: Will be added to the movement computation (pixels).
     * @param scroll_time: Number. Time in ms that the transition should take. 200 is a good value. */
    function scroll_to(id_container, id_target, additional_offset, scroll_time)
    {
      //> Preliminaries. -------------------------------------------------
      if (additional_offset===undefined) { additional_offset=0; }
      if (scroll_time===undefined) { scroll_time=200; }
      var cont = $("#"+id_container);
      var target = $("#"+id_target);
      //< ----------------------------------------------------------------
      //> Actual strolling scrolling. ------------------------------------
      var site = target.position().left + additional_offset - cont.innerWidth()/2.0 + cont.scrollLeft();
      cont.animate({ scrollLeft: site }, scroll_time);
      //< ----------------------------------------------------------------
    }
    

    顺便说一句:整个动画实际上只是一点糖。核心解决方案是在周围容器上设置 CSS 属性:scrollLeft。参见,例如,这里: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft

    【讨论】:

    • 非常感谢您抽出宝贵时间回答我的问题。所有部分都覆盖了 100% 的页面并与 z-index 重叠。如果我向您展示我的 codepen 项目,您可以查看css代码codepen.io/ibrahimgedik/pen/ZEWRvYV你可以在这里查看,我无法处理它,因为我对javascript没有经验。当我点击 Home 时我想切换到第 1 部分,当我点击 关于 时切换到第 2 部分,当我点击 Portfolio
    • IC。也许您可以根据需要使用js动态设置/删除css样式属性'display:none'。使用 onclick 事件执行此操作。 w3schools.com/css/css_display_visibility.asp
    • 但也许你真正想要实现的是标签:w3schools.com/howto/howto_js_tabs.asp
    猜你喜欢
    • 1970-01-01
    • 2011-08-09
    • 2017-04-08
    • 1970-01-01
    • 2021-05-31
    • 2016-02-08
    • 1970-01-01
    • 2017-02-08
    • 2014-06-25
    相关资源
    最近更新 更多