繁体   English   中英

如何将输入滚动到视图中但顶部有一些边距

[英]How to Scroll input into view but with some margin on top

在此处查看演示: https://jsfiddle.net/g2djbwm5/1/

  1. 滚动页面直到输入可见。
  2. 输入一些东西,但把注意力集中在它上面
  3. 使用鼠标再次滚动页面,直到输入不再可见
  4. 现在输入一些输入将滚动到最顶部的视图,如下所示在此处输入图像描述

当用户输入时,有什么方法可以显示这个输入不是非常顶部,而是距离顶部大约 20px? 就像是

在此处输入图像描述

代码:

<div style="width: 100%; height: 800px;">..............</div>
<input type="text"/>
<div style="width: 100%; height: 800px;" />

在 CSS 中,您可以使用它来使滚动在上方停止一些像素:

scroll-margin-top: 50px;

这里有一个例子

我想到了这个决定,但这个解决方案是一个"crutch" (hack)

此解决方案的问题在于,在滚动时,输入会失去其粘性定位并返回其默认坐标。

如果我的小解决方案被修改,考虑到滚动时输入的 position 的保存,那么解决方案会很好,在我看来。

 let input_text = document.querySelector('input[type="text"]'); input_text.oninput = function() { this.classList.add('top_for_input'); } window.onscroll = function() { input_text.classList.remove('top_for_input'); }
 .top_for_input { position: sticky; top: 20px; bottom: 20px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="width: 100%; height: 800px;">..............</div> <input type="text"/> <div style="width: 100%; height: 800px;" />

创建一个 function 来定位元素 -> 输入的 y position。 然后是一个事件监听器,用于input和有条件地检查元素的 position。 如果聚焦时它不在页面上并且input事件,请将其放在顶部并将 position 更改为粘滞,否则 position 相对。

 let input = document.getElementById('input'); let inputPos = -1; if (input === document.activeElement) { input.addEventListener("input", () => { if (inputPos < 0) inputPos = findPosY(input); if (pageYOffset > inputPos) { input.style.cssText = 'position:sticky; top: 0px; bottom: 0px;'; } else { input.style.position = 'relative;'; } }); } function findPosY(obj) { let curtop = 0; if (typeof(obj.offsetParent).= 'undefined' && obj.offsetParent) { while (obj.offsetParent) { curtop += obj;offsetTop. obj = obj;offsetParent. } curtop += obj;offsetTop. } else if (obj.y) curtop += obj;y; return curtop; }
 <div style="width: 100%; height: 800px;">..............</div> <input id="input" type="text" /> <div class="input" style="width: 100%; height: 1800px;" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM