JavaScript之HTML与CSS属性操作

A.HTML

1.获取静态HTML属性值
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input  />
</body>
<script>
    function func() {
        var oBtn = document.getElementById("btn");
        oBtn.onclick = function () {
            alert(oBtn.id)
        }
    }
    func()
</script>
</html>
2.获取动态HTML属性值
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <label><input type="radio" name="fruit" value="苹果" checked/>苹果</label>
        <label><input type="radio" name="fruit" value="香蕉" checked/>香蕉</label>
        <label><input type="radio" name="fruit" value="西瓜" checked/>西瓜</label>
    </div>
    <input  />
</body>
<script>
    function func() {
        var oBtn = document.getElementById("btn");
        var oFruit = document.getElementsByName("fruit");
        oBtn.onclick = function () {
            for (var i=0;i<oFruit.length;i++) {
                if (oFruit[i].checked) {
                    alert(oFruit[i].value);
                }
            }
        };
    }
    func()
</script>
</html>

效果如图:

JavaScript之HTML与CSS属性操作

2.1 获取文本框的值
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input />
    <input  />
</body>
<script>
    function func() {
        var oBtn = document.getElementById("btn");
        oBtn.onclick = function () {
            var oTxt = document.getElementById("txt");
            // 注意里用的是value属性
            alert(oTxt.value)
        }
    }
    func()
</script>
</html>

对于其他的表单元素同样都是通过value属性来获取内容的。

3. 设置HTML属性值。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input  />
</body>
<script>
    function func() {
        var oBtn = document.getElementById("btn");
        oBtn.onclick = function () {
            oBtn.value = "button";
        };
    }
    func()
</script>
</html>

对于对象方法,一共有四种:getAttribute(),setAttribute(), removeAttribute(),hasAttribute()。这个看字面意思非常好理解,类似obj.getAttribute(“attr”)等同于obj.attr。不同的是,对于自定义的属性的获取修改删除等,只能使用前面的方法。

B.CSS属性操作

1.获取CSS属性值
getComputedStyle(obj).attr

如果CSS是font-size,attr就写成fontSize,没错就是驼峰体。注意不要使用obj.style.attr。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #box {
             100px;
            height: 100px;
            background-color: hotpink;
        }
    </style>
</head>
<body>
    <input  />
    <div ></div>
</body>
<script>
    function func() {
        var oBtn = document.getElementById("btn");
        var oBox = document.getElementById("box");
        oBtn.onclick = function () {
            alert(getComputedStyle(oBox).backgroundColor);
        };
    }
    func()
</script>
</html>
2.设置CSS属性值

最简单的就是使用style对象:

obj.style.attr = “值”,attr和“值”均使用驼峰体。

也可以是cssText属性。

obj.style.cssText = “值”,值用正常的css样式。