JS页面操作

一、鼠标事件

/*
onclick:鼠标点击
ondblclick:鼠标双击
onmousedown:鼠标按下
onmousemove:鼠标移动
onmouseup:鼠标抬起
onmouseover:鼠标悬浮
onmouseout:鼠标移开
oncontextmenu:鼠标右键
*/

二、事件的绑定

2.1 具体绑定事件的方式:

<body>
    <div class="box">绑定点击事件后可以完成点击交互</div>
    <script>
        var box = document.querySelector('.box');
        // 页面class为box的div被鼠标点击后会有弹出框
        box.onclick = function() {
            alert("box标签被点击了")
        }
    </script>
</body>

2.2 操作页面标签

2.2.1 操作行间式样式

<head>
    <style>
        .box {
            width: 200px;
            height: 200px;
        }
    </style>
</head>
<body>
    <div class="box" style="background-color: red"></div>
    <script>
        var box = document.querySelector('.box');
        // 语法:页面对象.全局style属性.具体的样式名
        box.onclick = function() {
            // 读:获取行间式样式值 
            var bgColor = box.style.backgroundColor;  
            // 写:对行间式样式进行赋值,初始没有该条行间式样式,相同会自动添加设置好的行间式
            box.style.backgroundColor = 'orange';  // css3多个单词的属性名采用小驼峰命名法
        }
    </script>
</body>

2.2.2 只读 计算后 样式

<head>
    <style>
        .box {
            width: 200px;
            height: 200px;
        }
    </style>
</head>
<body>
    <div class="box" style="background-color: red"></div>
    <script>
        var box = document.querySelector('.box');
        // 语法:getComputedStyle(页面元素对象, 伪类).样式名;
        // 注:我们不需要考虑伪类的范畴,直接用null填充即可
        box.onclick = function() {
            // 只读:获取计算后样式值 
            var width = getComputedStyle(box, null).width;  
        }
    </script>
</body>

2.2.3 操作标签class名

<body>
    <div class="box">class名操作</div>
    <script>
        var box = document.querySelector('.box');
        // 查看类名
        var cName = box.className;
        // 修改类名
        box.className = "ele";
        // 增加类名
        box.className = " tag";  // 添加后的结果class="ele tag",所以赋值时一定注意tag前有个空格字符串
        // 删除所有类名
        box.className = "";
    </script>
</body>

2.2.4 操作标签全局属性值

<body>
    <img src="https://www.baidu.com/favicon.ico" class="image" />
    <script>
        var img = document.querySelector('.image');
        // 查看全局属性值
        var imgSrc = img.getAttribute('src');
        // 修改全局属性值
        img.setAttribute('src', 'img/bg_logo.png');
        // 删除全局属性值
        img.setAttribute = ('src', '');;
    </script>
</body>

 

posted on 2020-02-14 15:38  软饭攻城狮  阅读(205)  评论(0)    收藏  举报

导航