onmousemove: 鼠标移动到元素时触发
onmouseleave: 鼠标离开元素时触发
#index.html
<<head><head>
<meta charset="utf-8">
<script type="text/javascript" src="index.js">
</script>
<style>
p {
background-image: url('test.png');
}
</style>
</head>
<body>
<p class='background' onmousemove="changeColor(this)" onmouseleave="changeColorBack(this)">The first paragraph</p>
<p class="background" onmousemove="changeColor(this)" onmouseleave="changeColorBack(this)">The second paragraph</p>
<p class="background" onmousemove="changeColor(this)" onmouseleave="changeColorBack(this)">The third paragraph</p>
</body>
<footer></footer>
#index.js
function changeColor(x) {
x.style.background = 'yellow';
}
function changeColorBack(x) {
x.style.background = 'white';
}
效果如图,当鼠标移动到元素上时,改变背景颜色为黄色;鼠标离开时,背景恢复为白色:
hover(更新:2017-08-04)
上述方法存在一个问题,当有背景图片时,触发效果后会破坏背景图片,使用hover不会
<!DOCTYPE html>
<html>
<header>
<style>
p:hover {
background: yellow;
}
body {
background-image: url('hello_python.png');
}
</style>
</header>
<body>
<p>The first paragraph</p>
<p>The second paragraph</p>
<p>The third paragraph</p>
</body>
</html>