用闭包实现事件传参

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: goldenrod;
            position: absolute;
            left: 0;
        }
    </style>
</head>
<body>
    <button id="btn1">按钮1</button>
    <button id="btn2">按钮2</button>
    <div class="box" id="box"></div>
</body>
</html>
<script>
    var btn1=document.getElementById("btn1");
    var btn2=document.getElementById("btn2");
    var box=document.getElementById("box");
    function move(speed) {
        return function () {
            box.style.left=box.offsetLeft+speed+"px";
        }
    }
    btn1.onclick=move(5);
    btn2.onclick=move(-5);
</script>

 

IT文库 » 用闭包实现事件传参
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址