前端html通过鼠标操作进行样式的更改
目标效果
第一种情况: 鼠标悬浮在上方,样式更改,鼠标离开后还原。css方式
第二种情况: 鼠标点击后,样式更改,鼠标松开后还原。css方式
第三种情况: 鼠标点击并松开后,样式更改。javascript方式
第四种情况: 鼠标点击后,样式更改,鼠标松开后样式不变。javascript方式
第五种情况: 鼠标点击并松开后,样式更改,鼠标离开后还原。javascript方式
第六种情况: 鼠标悬浮在上方,样式更改,鼠标离开后样式不变。javascript方式
代码
备注:email_black.png和email_white.png可以是任意两张不同的图片
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<style>
//第一种情况
.test1 {
background-image: url(img/email_black.png);
width: 50px;
height: 50px;
}
.test1:hover {
background-image: url(img/email_white.png);
width: 50px;
height: 50px;
}
//第二种情况
.test2 {
background-image: url(img/email_black.png);
width: 50px;
height: 50px;
}
.test2:active {
background-image: url(img/email_white.png);
width: 50px;
height: 50px;
}
//第三种情况
.test3 {
background-image: url(img/email_black.png);
width: 50px;
height: 50px;
}
.test3-click {
background-image: url(img/email_white.png);
width: 50px;
height: 50px;
}
//第四种情况
.test4 {
background-image: url(img/email_black.png);
width: 50px;
height: 50px;
}
.test4-hover {
background-image: url(img/email_white.png);
width: 50px;
height: 50px;
}
//第五种情况
.test5 {
background-image: url(img/email_black.png);
width: 50px;
height: 50px;
}
.test5-active {
background-image: url(img/email_white.png);
width: 50px;
height: 50px;
}
//第六种情况
.test6 {
background-image: url(img/email_black.png);
width: 50px;
height: 50px;
}
.test6-hover {
background-image: url(img/email_white.png);
width: 50px;
height: 50px;
}
</style>
<body>
<div>
<div class="test1"></div>
<div class="test2"></div>
<div class="test3" id="test3" onclick="doclick()"></div>
<div class="test4" id="test4" onmousedown="domousedown_test4()"></div>
<div class="test5" id="test5" onmousedown="domousedown_test5()" onmouseout="domouseout_test5()"></div>
<div class="test6" id="test6" onmouseover="domouseover_test6()"></div>
</div>
</body>
<script>
function doclick(){
var elem = document.getElementById("test3");
if(elem.getAttribute("class")=="test3"){
elem.setAttribute("class","test3-click");
}else{
elem.setAttribute("class","test3");
}
}
function domousedown_test4(){
var elem = document.getElementById("test4");
if(elem.getAttribute("class")=="test4"){
elem.setAttribute("class","test4-hover");
}else{
elem.setAttribute("class","test4");
}
}
function domouseout_test5(){
var elem = document.getElementById("test5");
elem.setAttribute("class","test5");
}
function domousedown_test5(){
var elem = document.getElementById("test5");
elem.setAttribute("class","test5-active");
}
function domouseover_test6(){
var elem = document.getElementById("test6");
if(elem.getAttribute("class")=="test6"){
elem.setAttribute("class","test6-hover");
}else{
elem.setAttribute("class","test6");
}
}
</script>
</html>