最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent mobile safari from scrolling page when textarea focused - Stack Overflow

programmeradmin3浏览0评论

As the title suggests, I need a workaround to prevent mobile safari from scrolling the document when a textarea is focused. The default behavior is to scroll the page so the textarea's top is aligned with the top of the window. I just want my page to stay put. Is this possible?

As the title suggests, I need a workaround to prevent mobile safari from scrolling the document when a textarea is focused. The default behavior is to scroll the page so the textarea's top is aligned with the top of the window. I just want my page to stay put. Is this possible?

Share Improve this question asked Dec 25, 2011 at 5:35 user1022241user1022241 2
  • 1 Take a look at this – tipycalFlow Commented Mar 4, 2012 at 5:30
  • so, you want the textarea hidden behind the soft keyboard? – marko Commented Mar 4, 2012 at 7:53
Add a ment  | 

2 Answers 2

Reset to default 6

try with this

// javascript.js
var locked_scroll = false;
var last_pos = 0;

document.getElementById('my-text').addEventListener('focus', function(event){
    console.log('set locked');
    locked_scroll = true;
    last_pos = document.getElementById('wrapper').scrollTop
});

document.getElementById('my-text').addEventListener('blur', function(event){
    console.log('set unlocked');
    locked_scroll = false;
});

document.getElementById('wrapper').addEventListener("scroll", function(event){

    if(locked_scroll) {
        event.target.scrollTop = last_pos;
    }

}, true);

the event scroll only works when the element have a fixed height and the overflow property set to auto or scroll

#wrapper {
    height: 300px;
    overflow: auto;    
}

check the example: http://jsfiddle/4YkNj/

Try this:

<script type="text/javascript">
   function blockMove() {
      event.preventDefault() ;
}
</script>

and

<input name="textbox" type="text" value="" onkeyup="blockMove;"/>

Maybe you need a timer to allow the browser to scroll the textarea to top before blocking the movement.

发布评论

评论列表(0)

  1. 暂无评论