前端基础之滚动及锚点

滚动相关

Element.scroll()

scroll() 方法是用于在给定的元素中滚动到某个特定坐标的 Element 接口。当前元素为可滚动的元素即外层元素

scroll(x-coord, y-coord)
scroll(options)
//参数
x-coord 到达位置水平轴像素值
y-coord 到达位置垂直轴像素值

options:{
  top:y轴像素值,
  left:x轴像素值,
  behavior: 过度效果 (smooth, auto)
}

Element.scrollBy()

scrollBy() 方法是使得元素滚动一段特定距离的 Element 接口。当前元素为可滚动元素。参数同 scroll();

Element.scrollIntoView()

Element接口的 scrollIntoView() 方法会滚动元素的父容器,使被调用 scrollIntoView() 的元素对用户可见。当前元素为可滚动元素的子元素。

element.scrollIntoView({ block: "end" });
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });

//参数
behavior 
定义滚动是立即的还是平滑的动画。
smooth:滚动应该是平滑的动画。
instant:滚动应该通过一次跳跃立刻发生。
auto:滚动行为由 scroll-behavior 的计算值决定。
block 
定义垂直方向的对齐,start、center、end 或 nearest 之一。默认为 start。
inline 
定义水平方向的对齐,start、center、end 或 nearest 之一。默认为 nearest。
  • 实例-在react中使用
    const scrollToBox=()=>{
        const element = document.getElementById('content');  
        if (element) {  
            element.scroll(0,500)
            //element.scrollBy(0,500)
            //element.scrollIntoView({ behavior: 'smooth' });  
        } 
    }
    return <div>
        <div style={{height:'80vh',width:'80%',overflow:'scroll'}} id='content'>
        <button onClick={scrollToBox}>滑动</button>
        <div style={{height:'500px'}}></div>
        <div style={{height:'200px',background:'blue',margin:'20px'}} id="content-title"></div>
        <div style={{height:'1000px'}}></div>
        </div>
    </div>
  

锚点

<a>

a元素(或称锚元素)可以通过它的 href 属性创建通向其他网页、文件、电子邮件地址、同一页面内的位置或任何其他 URL 的超链接。

<!-- <a> 元素链接到下面部分 -->
<p><a href="#Section_further_down"> 跳转到下方标题 </a></p>

<!-- 要链接到的标题 -->
<h2 id="Section_further_down">更下面的部分</h2>
  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值