js--对css类操作、对style样式操作、获取表单的值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            margin-bottom: 50px;
        }
        .box1{
            background-color: red;
        }
        .box2{
            background-color: green;
        }
        .box3{
            background-color: red;
        }
        .bor{
            border: 1px solid black;
        }
    </style>
</head>
<body>
<div id="box1" class="box1" onclick="change1()"></div>
<div id="box2" class="box2" onclick="change2()"></div>
</body>
<script>
    //使用行内事件的时候不能使用此方法
//    window.onload = function () {
    var box1 = document.getElementById("box1");
    var box2 = document.getElementById("box2");
         function change1() {
//            box1.className = 'box2';//js原始添加css类
//            box1.classList.add("box2","bor");//添加,添加多个样式用‘,’隔开
//            box1.classList.remove("类名");//移除,移除多个样式用‘,’隔开
//            box1.classList.contains("类名");//检查是否含有某个CSS类 return true or false
             box1.classList.toggle("box2");//切换css类

        }
        function change2() {
            box2.classList.toggle("box3");
        }
//    }
</script>
</html>

从标签中读取到的值为字符串。

对style中属性操作:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="div" width="300px" style="width: 200px;height: 200px; border: 1px solid red;" onclick="change()" ></div>
</body>
<script>
    //对标签中属性的操作    对象.属性名(获取值)
    function change() {
//对象放在函数里面,原因每次发生点击事件就要获得对象
        var div = document.getElementsByClassName("div")[0];
//    console.log(div.style);打印出样式对象
//    alert(div.style.width);style属性中样式的操作   对象.style.属性名
var w = div.style.width ; var h = parseInt(div.style.height) ; // w = parseInt(w)+20+"px";这里不可取,原因 不是直接获取到对象上的属性 div.style.width = parseInt(w) + 20 + "px" ; div.style.height = h + 20 + "px" ; }</ script></ html>




获取表单的输入值:

对象.value  属性进行获取

<body>
姓名:<input type="text" name="name" oninput="copy()">
<br>
复制姓名:<input type="text" name="copy">

</body>
<script>
    function copy() {
        var inp = document.getElementsByTagName("input");
        //获取表单的值  通过value属性
        inp[1].value = inp[0].value;
    }
</script>



为编辑完,待续……



若有不足请多多指教!希望给您带来帮助!

猜你喜欢

转载自blog.csdn.net/muzidigbig/article/details/80839423
今日推荐