分享一个页面滑腻转动小能力(保举)
本日写需求的时辰发明一个小的优化点:用户选择了一些数据之后, 对应列表中的数据必要高亮, 偶然辰列表很长, 为了晋升用户体验,必要加个转动, 自动转动到方针位置。 简朴的处理赏罚了一下, 题目顺遂办理, 就把这个小能力分享一下给各人。 正文 有几种差异的方法来办理这个小题目。 1.scrollTop 第一想到的照旧scrollTop, 获取元素的位置, 然后直接配置: // 配置转动的间隔 element.scrollTop = value; 不外这样子有点生硬, 可以加个缓动: var scrollSmoothTo = function (position) { if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { return setTimeout(callback, 17); }; } // 当前转动高度 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 转动step要领 var step = function () { // 间隔方针转动间隔 var distance = position - scrollTop; // 方针转动位置 scrollTop = scrollTop + distance / 5; if (Math.abs(distance) < 1) { window.scrollTo(0, position); } else { window.scrollTo(0, scrollTop); requestAnimationFrame(step); } }; step(); }; // 滑腻转动到顶部,可以直接: scrollSmoothTo(0) jQuery 中重的animate 要领也可以实现相同的结果: $('xxx').animate({ scrollTop: 0 }); 2. scroll-behavior 把 scroll-behavior:smooth; 写在转动容器元素上,也可以让容器(非鼠标手势触发)的转动变得滑腻。 .list { scroll-behavior: smooth; } 在PC上, 网页默认转动是在<html>标签上的,移动端大大都在<body> 标签上, 那么这行界说到全局的css中就是: html, body { scroll-behavior:smooth; } 美滋滋。 3. scrollIntoView Element.scrollIntoView() 要领, 让当前的元素转动到赏识器窗口的可视地区内。 语法: var element = document.getElementById("box"); element.scrollIntoView(); // 等同于element.scrollIntoView(true) element.scrollIntoView(alignToTop); // Boolean型参数 element.scrollIntoView(scrollIntoViewOptions); // Object型参数 scrollIntoView 要领接管两种情势的值: 布尔值 假如为true,元素的顶端将和其地址转动区的可视地区的顶端对齐。 响应的 scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是这个参数的默认值。 假如为false,元素的底端将和其地址转动区的可视地区的底端对齐。 响应的scrollIntoViewOptions: { block: "end", inline: "nearest" }。Options 工具 { behavior: "auto" | "instant" | "smooth", 默以为 "auto"。 block: "start" | "end", 默以为 "start"。 inline: "start"| "center"| "end", | "nearest"。默以为 "nearest"。 } behavior暗示转动方法。auto暗示行使当前元素的scroll-behavior样式。instant和smooth暗示直接滚到底和行使滑腻转动。 block暗示块级元素分列偏向要转动到的位置。对付默认的writing-mode: horizontal-tb来说,就是竖直偏向。start暗示将视口的顶部和元素顶部对齐;center暗示将视口的中间和元素的中间对齐;end暗示将视口的底部和元素底部对齐;nearest暗示就近对齐。 inline暗示行内元素分列偏向要转动到的位置。对付默认的writing-mode: horizontal-tb来说,就是程度偏向。其值与block相同。 scrollIntoView 赏识器兼容性 最后我用的是 scrollIntoView, 题目美满办理。 (编辑:河北网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |