当前页面,点击右侧导航栏,去到页面指定的地方

         <div id="tab1" >111</div>
         <div id="tab2" >222</div>
         <div id="tab3" >333</div>
         <div id="tab4" >444</div>

假设该div里的111是要定位的内容

          <div class="navbar">
            <ul>
              <li><a href="#" onclick=" window.location.href = '#tab1'">111</a></li>
              <li><a href="#" onclick=" window.location.href = '#tab2'">222</a></li>
              <li><a href="#" onclick=" window.location.href = '#tab3'">333</a></li>
              <li><a href="#" onclick=" window.location.href = '#tab4'">444</a></li>
            </ul>
          </div>

写一个οnclick=" window.location.href = '#tab1'"即可,点击过去即可到111在的地方

样式如下:

.navbar {
  background-color: #f8f9fa;
  padding: 10px;
  margin-top: 31px;
}
.navbar ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
.navbar ul li {
  margin-bottom: 5px;
}
.navbar ul li a {
  text-decoration: none;
  color: #333;
  display: block;
  padding: 5px;
}
.navbar ul li a:hover {
  background-color: #e9ecef;
}

效果图:

以下是一个简单的示例代码,实现了一个顶部导航栏点击右边的标题会跑到中间: ``` <template> <div class="nav"> <div class="nav-left"> <span class="nav-title">左侧标题</span> </div> <div class="nav-center"> <span class="nav-title">{{ currentTitle }}</span> </div> <div class="nav-right"> <span class="nav-title" @click="scrollToCenter">右侧标题</span> </div> </div> </template> <script> export default { data() { return { currentTitle: '中间标题' } }, methods: { scrollToCenter() { // 获取中间标题的位置 const centerTitle = document.querySelector('.nav-center .nav-title') const centerTitleRect = centerTitle.getBoundingClientRect() const centerTitleOffset = centerTitleRect.left + centerTitleRect.width / 2 // 滚动到中间标题的位置 window.scrollTo({ left: centerTitleOffset - window.innerWidth / 2, behavior: 'smooth' }) } } } </script> <style scoped> .nav { display: flex; align-items: center; justify-content: space-between; height: 50px; background-color: #eee; font-size: 18px; font-weight: bold; padding: 0 20px; } .nav-title { cursor: pointer; } .nav-center { flex-grow: 1; text-align: center; } </style> ``` 在这个示例中,顶部导航栏被划分为三个部分:左侧、中间和右侧。中间部分显示当前的标题,右侧部分的标题被点击时,页面会滚动到中间标题的位置。 为了实现滚动效果,我们使用了 `window.scrollTo()` 方法,将页面滚动到指定的位置。在这个方法中,我们需要传入一个对象,包含两个属性:`left`(水平滚动距离)和 `behavior`(滚动行为,可以是 "auto"、"smooth" 或 "instant")。 注意,在 `scrollTo()` 方法中计算滚动距离时,我们使用了 `window.innerWidth` 属性,这是窗口的内部宽度,也就是视口的宽度,不包括滚动条的宽度。我们可以用这个属性计算出中间标题的位置和窗口的滚动距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值