Heim >Web-Frontend >H5-Tutorial >怎样用 JavaScript 准确获取手机屏幕的宽度和高度?
<code class="language-html"><span class="cp">
<span class="nt"></span>
<span class="nt"></span>
<span class="nt"><meta> <span class="na">name=</span><span class="s">"viewport"</span> <span class="na">content=</span><span class="s">"width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"</span><span class="nt">/></span>
<span class="nt"><title></title></span>Document<span class="nt"></span>
<span class="nt"></span>
<span class="nt"></span>
<span class="nt"></span>
<span class="nt"></span>
</span></span></code>
window.innerHeight属性,window.innerWidth属性
这两个属性返回网页的CSS布局占据的浏览器窗口的高度和宽度,单位为像素。很显然,当>用户放大网页的时候(比如将网页从100%的大小放大为200%),这两个属性会变小。
注意,这两个属性值包括滚动条的高度和宽度。
screen对象screen对象包含了显示设备的信息。
- screen.height:显示设备的高度,单位为像素。
- screen.width:显示设备的宽度,单位为像素。
以上两个属性,除非调整显示设备的分辨率,否则看作是常量,不会发生变化。
下面是根据屏幕分辨率,将用户导向不同网页的代码。
<code class="language-js"><span class="k">if</span> <span class="p">((</span><span class="nx">screen</span><span class="p">.</span><span class="nx">width</span><span class="o"><span class="mi">800</span><span class="p">)</span> <span class="o">&&</span> <span class="p">(</span><span class="nx">screen</span><span class="p">.</span><span class="nx">height</span><span class="o"><span class="mi">600</span><span class="p">))</span> <span class="p">{</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="s1">'small.html'</span><span class="p">);</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="s1">'wide.html'</span><span class="p">);</span>
<span class="p">}</span>
</span></span></code>