从javascript函数获取屏幕宽度并以百分比形式使用

时间:2013-08-08 10:28:59

标签: javascript html

我必须根据屏幕的宽度调整表格元素的大小。我不知道javascript或html,但我必须让它工作。我没有写原始的asp页面,我也无法改变它。

例如,在下面的代码示例中,SCREENWIDTH是变量或函数调用的占位符:

<td>
  <div style="width:(SCREENWIDTH * 2 / 3)%">
    <input type="text" class="textfield" id="resourceref" name="resourceref"
      accesskey="E" onkeydown="infoChange('ref');" style="width: 90%">
  </div>
</td>

我正在考虑使用javascript函数,我在其中调用screen.width,并将其作为SCREENWIDTH的值返回,但是我的语法似乎不正确我是否将函数调用放入“和“或'和'。

也许有另一种方法可以做到这一点,但这是我的推理。

它被编码为简单的百分比,但它无法正常工作。该td位于表格中,该表格位于作为三个垂直帧的帧集的一部分的帧中,并且如果屏幕宽度非常窄,则在右侧存在另一个遮挡一些表格元素的帧。我没有这样写,我不太了解帧,但我必须解决这个问题。所以我想知道屏幕宽度是多少,并在我用它来确定td的宽度之前适当调整它。

所以如果我有(并且除了简单地返回之外我可能会对屏幕宽度做更多的事情)

<script language="javascript">
function getScreenWidth()
{
    return screen.width; 
}
</script>
在head标签中

,我该如何从html中调用它?

那么如何确定屏幕的宽度作为确定td宽度的一部分呢?

3 个答案:

答案 0 :(得分:0)

应该能够screen.width获取屏幕宽度(以像素为单位)。但是,在这种情况下,您是否有特殊原因使用width: 66.666%

答案 1 :(得分:0)

屏幕宽度和高度很棘手,因为不同的浏览器会处理它不同。 我建议看看jquery有一些有用的工具来调整大小。特别是关于调整大小事件等。

以下是一个例子:

         $(window).resize(function() {   
           // event which gets fired on rezising
            $(window).height(); // the new height 
            $(window).width(); // the new width
          });

您可以使用此信息进行进一步的计算和样式设计......

例如

    $('#theDiv').width(function(){
   return $(window).width() * 0.66;
});

它的工作不引人注目(没有内联javascript)只给div一个ID HTH

答案 2 :(得分:0)

我使用我编写的这个函数正确地报告了我尝试过的每个设备......

这样您就可以根据实际屏幕尺寸计算百分比。我从iPad宽度(768)开始,从那里开始计算% - (screenWidth / 768)* 100 ..

希望这有帮助。

function getDeviceDimensions()                  // get the width and height ofthe viewing device based on its OS
{
    screenWidth = window.screen.width;                                                  // get the width
    screenHeight = window.screen.height;                                                // get the height 
    var computedPixelRatio =  (window.screen.availWidth / document.documentElement.clientWidth);                        // a more reliable measure of device pixel ratio due to android firefox bugs...
    computedPixelRatio = window.devicePixelRatio >= computedPixelRatio ? window.devicePixelRatio : computedPixelRatio;  // select whichever value is larger between pixel ratio methods
    if (navigator.userAgent.indexOf('Android') != -1)                                   // if the client is on an android system
    {
        screenWidth = screenWidth / computedPixelRatio;                                 // divide the reported width by the pixel ratio
        screenHeight = screenHeight / computedPixelRatio;                               // divide the reported height by the pixel ratio
    }
    //alert(screenWidth + " " + screenHeight + " " + window.devicePixelRatio + " " + computedPixelRatio);
}