[英]How to Scroll input into view but with some margin on top
在此处查看演示: https://jsfiddle.net/g2djbwm5/1/
当用户输入时,有什么方法可以显示这个输入不是非常顶部,而是距离顶部大约 20px? 就像是
代码:
<div style="width: 100%; height: 800px;">..............</div>
<input type="text"/>
<div style="width: 100%; height: 800px;" />
我想到了这个决定,但这个解决方案是一个"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.