2019-03-04

2019-03-04  本文已影响0人  Mrs祝

按钮上绑定事件

<div id="a">abc</div>
<button id="test" >test</button>
<script>
    // // 文档对象
    // let  m=document.getElementById("a")
    // //innerHTML找属性
    // alert(m.innerHTML)
    function fn() {
        alert("hello")
    }
    // document.getElementById("test").onclick=fn;
//不同写法
    // document.getElementById("test").addEventListener("click",function () {
    //     alert("hello mrs")
    // });
    document.getElementById("test").addEventListener("click",()=> alert("hello mrs"))
</script>

获得div位置 每个时间会调整其位置

let/var 多用let 用来声明类型 ;;var可同时改变上面代码

常量‘’,真假值ture/flas

类型

数值,真假值,字符串,对象类型
.style 用来获得元素属性
通过计算得出数值:

  let x=window.getComputedStyle(m,null).left;

偏移

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #a{
            position: absolute;
            left: 200px;
            top: 300px;
            height: 300px;
            width: 300px;
            background-color: red;
        }
    </style>
</head>
<body>
<div id="a">abc</div>
<button id="test" >test</button>
<script>
//获得文档熟悉感
    let btn=document.getElementById("test")
//通过点击事件获得
    btn.onclick=function () {
        let  m=document.getElementById("a");
        //x.style.left
//获得计算元素值
        let x=window.getComputedStyle(m,null).left;
        let y=window.getComputedStyle(m,null).top;
//将px换为一个数字类型对象
     let a=Number.parseInt(x);
//对m对象下的元素样式进行改变
     m.style.left=(a+100)+"px";
    }
</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读