【问题标题】:css responsive design having difficulty accessing width with javascriptcss 响应式设计难以使用 javascript 访问宽度
【发布时间】:2013-05-05 12:50:52
【问题描述】:

我正在制作我的第一个响应式设计网站。我有一个使用像素和媒体查询设置的图像滑块 div。我希望能够访问宽度,以便我可以告诉图像滑块我需要移动多远。不幸的是,媒体查询似乎并没有改变 HTML。是否有任何解决方法来获取该信息,以便我可以在 javascript 中使用它。

这是一个简单的网页示例和一个 JSFiddle http://jsfiddle.net/synthet1c/sNbW9/

<!doctype html>
<html>

<head>

<style>

    body{
        position:absolute;
        background:red;
        width:100%;
        height:100%;
    }

    #outer{
        position:absolute;
        width:80%;
        height:80%;
        background:red;
        background-image:url('http://www.largepictures.net/largepictures/scenery/largepictures_scenery_large_3066.jpg');
        background-position: center;
        margin:auto;
    }

    #inner{
        width:80%;
        height:80%;
        background:rgba(255,0,0,0.3)
        margin:auto;
        margin-top:5%;
    }

</style>

    <script>

    document.getElementById('inner').onclick = function(){
        alert(document.getElementById('inner').style.width);
    }

    </script>   

</head> 

<body>

    <div id="outer">

        <div id="inner">click the box to get width</div>

    </div>

</body>
</html>

【问题讨论】:

    标签: javascript css responsive-design width


    【解决方案1】:

    element.style 对象仅适用于使用style 属性设置的属性(顾名思义)。要检索使用样式表设置样式的元素的 CSS 设置:

    document.getElementById('inner').onclick = function(){
        alert(window.getComputedStyle(document.getElementById('inner'), null).width);
    }
    

    JS Fiddle demo.

    参考资料:

    【讨论】:

      【解决方案2】:

      我为自己做了一个小sn-p,因为这是我一段时间以来一直需要的功能

      var comStyle = function(element , pseudoElt){ 
          if(!pseudoElt){pseudoElt = null} 
          return window.getComputedStyle(document.getElementById(element), pseudoElt); }
      

      这让我想到了……我是否能够更改原型,所以如果 element.style.something 等于且为空字符串,然后使用 getComputedStyle() 从样式表中获取实际值?

      【讨论】:

        【解决方案3】:

        你不能只使用offsetWidth,它是只读属性,以整数形式提供元素的宽度。

        var el = document.getElementById('inner')
        
        el.onclick = function(){
              alert(el.offsetWidth)
        }
        

        http://jsfiddle.net/t2r7jnb4/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-28
          • 2014-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-10
          • 1970-01-01
          相关资源
          最近更新 更多