从javascript获取样式设置的问题

时间:2016-02-03 01:26:53

标签: javascript html css

所以我试着这样做,所以每按一次按钮,圆圈就会变宽。我遇到了一个最特殊的问题,它们是一段代码,当你把它放在一个alert()方法时它会正确显示,但如果把它放入一个变量然后显示它就显示为nul。这是完整的代码。

<!doctype html>
<html>
<head>
 <title>CSS Basics</title>
 <meta charset="utf-8" />
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1" />
 <style>
    #circle {
        width:200px;
        height:200px;
        border-radius:200px;
        background-color:red;
    }
    </style>

</head>

<body>
    <div id="circle">asdfasdf</div>
    <button id="Saver"> Press me to save your text </button>
    <input id="Text" type="text" value="test"/>

    <script type="text/javascript">

        var divId="circle";
        var obj= document.getElementById("Saver");
        var it234 = 1;
        //THIS IS A COMMENT DOESNT THSI MAKE YOU  HAPPY
        obj.onclick=function() {

            document.getElementById("circle").innerHTML = document.getElementById("Text").value;
            it234 = parseInt(document.getElementById("circle").style.width.substring(0,3));
            //document.getElementById("circle").style.width="300px";
            alert(it234);
        }

    </script>
</body>
</html>

这是正在进行的部分

这应该有效,但不是

obj.onclick=function() {

            document.getElementById("circle").innerHTML = document.getElementById("Text").value;
            it234 = parseInt(document.getElementById("circle").style.width.substring(0,3));
            //document.getElementById("circle").style.width="300px";
            alert(it234);
        }

然而,不是工作,它显示与南的警报。如何将此div的宽度保存到变量中(最好是字符串格式)?

2 个答案:

答案 0 :(得分:4)

Javascripts element.style只返回内联样式,而不是样式表或样式标记中设置的样式,因此document.getElementById("circle").style.width不返回任何内容,只返回一个空字符串,并将其解析为整数返回NaN(不数字)。

使用getComputedStyle可以获得计算出的样式

var divId = "circle";
var obj = document.getElementById("Saver");
var it234 = 1;

obj.addEventListener('click', function() {

    document.getElementById("circle").innerHTML = document.getElementById("Text").value;
    console.log(document.getElementById("circle").style.width)

    var elem  = document.getElementById("circle");
    var style = window.getComputedStyle(elem);
    var width = style.getPropertyValue('width');

    it234 = parseInt( width.replace(/\D/g,'') );

    alert(it234);

}, false);

答案 1 :(得分:0)

使用element.offsetWidth获取宽度。