在Chrome中编辑粘性输入元素会导致页面滚动到顶部 [英] Editing a sticky input element in Chrome causes the page to scroll to the top
本文介绍了在Chrome中编辑粘性输入元素会导致页面滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我发现其中包含输入字段或文本区域之类的可编辑元素会触发页面滚动到顶部时,我试图在我的一个个人项目中使用css position:sticky
I was trying to use the css position: sticky
in one of my personal project when I noticed that having editable elements like input fields or text-areas inside, trigger the page to scroll to the top.
如果可能的话,我真的很想删除此行为.
I would really like to remove this behaviour if possible.
.container {
height: 5000px;
}
.heading{
background: #ccc;
height: 50px;
line-height: 50px;
margin-top: 10px;
font-size: 30px;
padding-left: 10px;
position: -webkit-sticky;
position: sticky;
top: 0px;
}
<h1>Lorem Ipsum</h1>
<div class="container">
<div class="heading">
<input placeholder="Edit this while scrolling...">
</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
</div>
推荐答案
您必须对密钥进行一些验证-最好使用正则表达式检查来确认可接受的字符,但是您可以从按键中调用javascript函数,更新输入的值,然后返回false:
You'll have to do some validation of the key - probably best with a regex check to confirm acceptable characters, but you can call a javascript function from the keypress, update the value of the input, and return false:
var e = document.getElementById('input');
e.onkeypress = myFunction;
function myFunction(t) {
document.getElementById('input').value += t.key;
return false;
}
.container {
height: 1000px;
}
.heading{
background: #ccc;
height: 50px;
line-height: 50px;
margin-top: 10px;
font-size: 30px;
padding-left: 10px;
position: -webkit-sticky;
position: sticky;
top: 0px;
}
<h1>Lorem Ipsum</h1>
<div class="container">
<div class="heading">
<input id="input" placeholder="Edit this while scrolling...">
</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
<div>Lorem Ipsum</div>
</div>
这篇关于在Chrome中编辑粘性输入元素会导致页面滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文