首页 > 技术文章 > js的那些事

yhxy 2021-03-30 18:48 原文

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 10px;
top: 100px;
}
</style>
</head>
<body>
<button onclick="show()">按钮</button>
<button onmouseover="show()">按钮</button>
<div class="box"></div>
<script>
function show(){
console.log("点击了");
}

var t;
function move(){
var box = document.querySelector(".box");
var left = parseInt( getComputedStyle(box)["left"] );
t = setInterval(function(){
left+=2;
box.style.left = `${left}px`;
},25);
}

move();

var box = document.querySelector(".box");
box.onmouseover = function(){ // onmouseover 鼠标选放
clearInterval(t);
};

// 一个元素本身可以绑定多个不同的事件, 但是如果多次绑定同一个事件,则后面的事件代码会覆盖前面的事件代码
box.onmouseout = function(){ // onmouseout 鼠标移开
move();
};

// 对于一个元素绑定事件有两种写法:
// 1. 静态绑定 ,直接把事件写在标签元素中
// <button onmouseover="show()">按钮</button>

// 2. 动态绑定,在js中通过代码获取元素对象,然后给这个对象进行后续绑定
/**
* var box = document.querySelector(".box");
box.onmouseover = function(){ // onmouseover 鼠标选放
clearInterval(t);
};
*/
</script>
</body>
</html>

推荐阅读