CSS响应式设计难以使用javascript访问宽度

css responsive design having difficulty accessing width with javascript

本文关键字:javascript 访问 响应 CSS      更新时间:2023-09-26

我正在制作我的第一个响应式设计网站。我有一个使用像素和媒体查询设置的图像滑块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>

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

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

JS Fiddle demo.

引用:

  • element.style .
  • window.getComputedStyle() .

我为自己编写了一小段代码,因为这是我需要一段时间的函数

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

这让我想到…我能够改变原型,所以如果element.style.something等于和空字符串,然后使用getComputedStyle()从样式表获得实际值?

你不能使用offsetWidth,它是一个只读属性,提供元素的宽度作为一个整数。

var el = document.getElementById('inner')
el.onclick = function(){
      alert(el.offsetWidth)
}
http://jsfiddle.net/t2r7jnb4/