0

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

3 回答 3

1

element.style对象仅适用于使用该属性设置的style属性(正如其名称所暗示的那样)。要检索使用样式表设置样式的元素的 CSS 设置:

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

JS 小提琴演示

参考:

于 2013-05-10T18:57:38.037 回答
0

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

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

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

于 2013-05-12T16:49:43.633 回答
0

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

var el = document.getElementById('inner')

el.onclick = function(){
      alert(el.offsetWidth)
}

http://jsfiddle.net/t2r7jnb4/

于 2019-06-29T17:38:49.620 回答