首页 期权学习期权知识正文

scrollIntoView()的用法

xiaojiucai 期权知识 2020-08-17 895 0

在滚动事件中绑定回调的应用场景非常多,如图片的懒加载、下滑自动加载数据、侧边浮动导航栏等,用户浏览网页时,拥有平滑滚动经常是被忽视但却是用户体验中至关重要的部分

scrollIntoView

  元素的scrollIntoView()方法支持一传入一个options,设置为smooth时,即可实现平滑滚动

ele.scrollIntoView({ behavior: 'smooth' })

  但是,该效果的兼容性不太好,移动端和IE都不支持

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			ul{
  padding: 0;
  margin: 0;
  list-style: none;
}

.con{
  width: 260px;
  display: flex;
  justify-content:space-around;
  line-height: 30px;
  background: #333;
  color: #fff;
}
.con li {
  cursor: pointer;
}
.showBox{
  width: 260px;
  height: 100px;
  overflow: hidden;
}
.show li {
  height: 100px;
  text-align: center;
  line-height: 100px;
  background: lightgreen;
}
.show li:nth-of-type(2){
	background: lightblue;
}
.show li:last-child{
	background: pink;
}
		</style>
	</head>
	<body>
		<ul class="con" id="con">
  <li>首页</li>
  <li>Html/Css</li>
  <li>JavaScript</li>
</ul> 
<div class="showBox">
  <ul class="show" id="show">
    <li>首页</li>
    <li>Html/Css</li>
    <li>JavaScript</li>
  </ul> 
</div>
<script type="text/javascript">
	  const con = document.getElementById('con')
  const show = document.getElementById('show')
  const showChildren = show.children
   Array.prototype.slice.call(con.children).map((item, index) => item.scrollTarget = showChildren[index])
  con.addEventListener('click', e => {
    const { target} = e
    if (target.nodeName === 'LI') {
      target.scrollTarget.scrollIntoView({ behavior: 'smooth' })
    }
  })
</script>
	</body>
</html>

效果图片展示(具体效果点上面的运行代码来看):

原文链接:https://www.qiquanji.com/post/8714.html

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。