+
95
-

js如何根据class的名字获取css属性代码?

请问js如何根据class的名字获取css属性代码?

网友回复

+
15
-

1、原生js这样来获取:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>js获取某元素的class里面的css属性值</title>
    <style>
        #box1 {
            margin: 5px;
            padding: 5px;
            height: 100px;
            width: 200px;
        }

        a {
            border: 1px solid #ccc;
            border-radius: 3px;
            padding: 3px 5px;
            margin: 5px 0;
            display: inline-block;
            background: #eee;
            color: #f60;
            text-decoration: none;
            font-size: 12px;
        }

        a:hover {
            color: #ff0000;
            background: #fff;
        }
    </style>
</head>

<body>
    <div id="box1">
        box1的css.#box1{margin:5px;padding:5px;height:100px;width:200px;}
    </div>
    <a id="href1" href="BfwJavascript;"BfwOnclick="getMarginTop()">获取box1的margin-top</a><br />
    <a href="BfwJavascript;"BfwOnclick="getcss('paddingTop')">获取box1的padding-top</a><br />
    <a href="BfwJavascript;"BfwOnclick="getcss('height')">获取box1的height</a><br />
    <script>
        //获取class里面的属性值
        var divs = document.getElementById("box1");

        function getStyle(obj, attr) {
            var ie = !+"\v1"; //简单判断ie6~8
            if (attr == "backgroundPosition") {
                //IE6~8不兼容backgroundPosition写法,识别backgroundPositionX/Y
                if (ie) {
                    return obj.currentStyle.backgroundPositionX + " " + obj.currentStyle.backgroundPositionY;
              ...

点击查看剩余70%

我知道答案,我要回答