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

javascript - window.scrollTo is not working in mobile phones - Stack Overflow

programmeradmin5浏览0评论

on my mobile view of my webpage i can scroll in vertical and horizontal direction, but this starts always at the top left corner. Now i want to set the viewport to my custom position with window.scrollTo or something equivalent. window.scroll seem just to work for desktop browser.

any idea how i could solve that?

on my mobile view of my webpage i can scroll in vertical and horizontal direction, but this starts always at the top left corner. Now i want to set the viewport to my custom position with window.scrollTo or something equivalent. window.scroll seem just to work for desktop browser.

any idea how i could solve that?

Share Improve this question asked Aug 7, 2012 at 11:52 SafariSafari 3,3829 gold badges49 silver badges66 bronze badges 3
  • Please be more specific as to what your issue is. window.scrollTo(x, y); works perfectly fine if your content is large enough. – Torsten Walter Commented Aug 7, 2012 at 11:54
  • My dom looks like this <body><div> <img /> </div></body> now i can scroll the within the image in mobile and desktop browsern. but when i what a different startposition, where i look at the image i try to use window. scrollTo(x, y); but this works only in the desktop not in the mobil browser. – Safari Commented Aug 7, 2012 at 11:59
  • Please provide a test case plete with html, css and JavaScript. Without knowing how large your image or how the dimensions of your content are, there is no possibility to gauge where the problem is. – Torsten Walter Commented Aug 7, 2012 at 12:07
Add a ment  | 

3 Answers 3

Reset to default 6

I got it finally working.

i had to use additionally the setTimeout function

setTimeout(() => window.scrollTo(x,y), 100);

I had the same problem, then I realized I had to consider the device Pixel Ratio to make it work well on mobile. It worked after I changed the meta tag in JavaScript like this:

document.querySelector("meta[name=viewport]").setAttribute('content', 'width=device-width, user-scalable=no, initial-scale='+(1/window.devicePixelRatio)+'');

I hope that helps those struggling with this.

As I said in my ment, this works if your content is large enough. This means larger than the viewport. Without knowing specifics, did you look into setting the viewport meta tag?

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Now, if your content div or image or whatever exceeds the size of the viewport width (320 dips on iPhone) you can scroll on the x axis. The same is true for the y axis with different values though.

发布评论

评论列表(0)

  1. 暂无评论