• CSS: overflow-anchor 固定滚动到底部,随着页面内容增多滚动条自己滚动展示最新的内容


    overflow-anchorCSS中的属性相对较新,2017 年首次推出 Chrome ¹,2019 年推出 Firefox,现在 Edge在 2020 年推出 Chrome 过渡。幸运的是,它的使用在很大程度上是一种增强。这个想法是浏览器在默认情况下确实尝试不允许位置移动。然后,如果您不喜欢它的处理方式,您可以使用 将其关闭。所以一般来说,你从不碰它。overflow-anchor 但正如你可能怀疑的那样,我们可以利用这个小美来做一点 CSS 小把戏。即使我们添加新内容,我们也可以强制滚动元素保持固定在底部。

    您需要检测何时使用 JavaScript 添加新内容并将滚动元素强制到底部。这是一种MutationObserver在 JavaScript 中使用的技术来监视新内容并强制滚动:

    1. const scrollingElement = document.getElementById("scroller");
    2. const config = { childList: true };
    3. const callback = function (mutationsList, observer) {
    4. for (let mutation of mutationsList) {
    5. if (mutation.type === "childList") {
    6. window.scrollTo(0, document.body.scrollHeight);
    7. }
    8. }
    9. };
    10. const observer = new MutationObserver(callback);
    11. observer.observe(scrollingElement, config);

    但我发现一个纯 CSS 的解决方案更有吸引力!上面的版本有一些我们稍后会介绍的用户体验缺陷。

    这里的诀窍是浏览器默认已经做了滚动锚定。但是浏览器试图做的不是改变你的页面。因此,当添加可能会改变页面视觉位置的新内容时,他们会尝试防止这种情况发生。在这种不寻常的情况下,我们有点想要相反的东西。我们希望页面卡在页面底部并让视觉页面在视觉上移动,因为它被迫保持卡在底部。

    下面是这个技巧的工作原理。首先是滚动父元素中的一些 HTML:

    1. <div id="scroller">
    2. <!-- new content dynamically inserted here -->
    3. <div id="anchor"></div>
    4. </div>

    所有元素自然都有一个overflow-anchor: auto;,这意味着当它们在屏幕上时,它们会试图阻止页面移动,但我们可以使用overflow-anchor: none;. 所以诀窍是针对所有动态插入的内容并将其关闭:

    1. #scroller * {
    2. overflow-anchor: none;
    3. }

    然后仅强制该锚元素具有滚动锚定,仅此而已:

    1. #anchor {
    2. overflow-anchor: auto;
    3. height: 1px;
    4. }

    现在,一旦该锚在页面上可见,浏览器将被迫将该滚动位置固定到它,并且由于它是该滚动元素中的最后一件事,因此保持固定在底部。

    1. <div id="scroller">
    2. <!-- new content dynamically inserted here -->
    3. <div id="anchor"></div>
    4. </div>
    5. <style>
    6. #scroller * {
    7. overflow-anchor: none;
    8. }
    9. #anchor {
    10. overflow-anchor: auto;
    11. height: 1px;
    12. }
    13. html {
    14. font-family: system-ui, sans-serif;
    15. }
    16. body {
    17. background-color: #7FDBFF;
    18. /* In case you need to kick off effect immediately, this plus JS */
    19. /* height: 100.001vh; */
    20. }
    21. .message {
    22. padding: 0.5em;
    23. border-radius: 1em;
    24. margin: 0.5em;
    25. line-height: 1.1em;
    26. background-color: white;
    27. }
    28. </style>
    29. <script>
    30. let scroller = document.querySelector('#scroller');
    31. let anchor = document.querySelector('#anchor');
    32. // https://ajaydsouza.com/42-phrases-a-lexophile-would-love/
    33. let messages = [
    34. 'I wondered why the baseball was getting bigger. Then it hit me.',
    35. 'Police were called to a day care, where a three-year-old was resisting a rest.',
    36. 'Did you hear about the guy whose whole left side was cut off? He’s all right now.',
    37. 'The roundest knight at King Arthur’s round table was Sir Cumference.',
    38. 'To write with a broken pencil is pointless.',
    39. 'When fish are in schools they sometimes take debate.',
    40. 'The short fortune teller who escaped from prison was a small medium at large.',
    41. 'A thief who stole a calendar… got twelve months.',
    42. 'A thief fell and broke his leg in wet cement. He became a hardened criminal.',
    43. 'Thieves who steal corn from a garden could be charged with stalking.',
    44. 'When the smog lifts in Los Angeles , U. C. L. A.',
    45. 'The math professor went crazy with the blackboard. He did a number on it.',
    46. 'The professor discovered that his theory of earthquakes was on shaky ground.',
    47. 'The dead batteries were given out free of charge.',
    48. 'If you take a laptop computer for a run you could jog your memory.',
    49. 'A dentist and a manicurist fought tooth and nail.',
    50. 'A bicycle can’t stand alone; it is two tired.',
    51. 'A will is a dead giveaway.',
    52. 'Time flies like an arrow; fruit flies like a banana.',
    53. 'A backward poet writes inverse.',
    54. 'In a democracy it’s your vote that counts; in feudalism, it’s your Count that votes.',
    55. 'A chicken crossing the road: poultry in motion.',
    56. 'If you don’t pay your exorcist you can get repossessed.',
    57. 'With her marriage she got a new name and a dress.',
    58. 'Show me a piano falling down a mine shaft and I’ll show you A-flat miner.',
    59. 'When a clock is hungry it goes back four seconds.',
    60. 'The guy who fell onto an upholstery machine was fully recovered.',
    61. 'A grenade fell onto a kitchen floor in France and resulted in Linoleum Blownapart.',
    62. 'You are stuck with your debt if you can’t budge it.',
    63. 'Local Area Network in Australia : The LAN down under.',
    64. 'He broke into song because he couldn’t find the key.',
    65. 'A calendar’s days are numbered.',
    66. ];
    67. function randomMessage() {
    68. return messages[(Math.random() * messages.length) | 0];
    69. }
    70. function appendChild() {
    71. let msg = document.createElement('div');
    72. msg.className = 'message';
    73. msg.innerText = randomMessage();
    74. scroller.insertBefore(msg, anchor);
    75. }
    76. setInterval(appendChild, 1000);
    77. // To kick off effect immediately, this plus CSS
    78. // document.scrollingElement.scroll(0, 1);
    79. </script>

    这里有两个小警告......

    1. 请注意,锚必须有一定的大小。我们在height这里使用以确保它不是没有大小的折叠/空元素,这会阻止它工作。
    2. 为了使滚动锚定起作用,页面必须至少滚动一次才能开始。

    第二个更难。一种选择是根本不处理它,您可以等待用户滚动到底部,效果从那里开始起作用。实际上这很好,因为如果他们从底部滚动,效果就会停止工作,这就是你想要的。在上面的 JavaScript 版本中,请注意即使您尝试向上滚动,它也会迫使您进入底部,这就是 Ryan 的意思,这并不是一件容易正确的事情。

    如果您需要立即启动效果,诀窍是让滚动元素立即可滚动,例如:

    1. body {
    2. height: 100.001vh;
    3. }

    然后立即触发一个非常轻微的滚动:

    document.scrollingElement.scroll(0, 1);

    这应该可以解决问题。这些行可在上面的演示中取消注释并尝试。

  • 相关阅读:
    软件设计师(十)网络与信息安全基础知识
    大数据必学Java基础(五十九):Map接口源码部分
    初级前端面试题之网络相关
    抽象类和接口的区别
    netty系列之:netty中的核心MessageToMessage编码器
    kubernetes学习笔记-ingress-nginx
    6.4.2 基于GZ文件安装MySQL
    [附源码]java毕业设计基于javaweb电影购票系统
    【SQL性能优化】索引的原理:我们为什么用B+树来做索引?
    java--switch语句
  • 原文地址:https://blog.csdn.net/liuhao9999/article/details/125500830