javascript - 一个元素绑定多个事件相互冲突的问题怎么解决?
本文介绍了javascript - 一个元素绑定多个事件相互冲突的问题怎么解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
项目中遇到的一个问题,总结为:同一元素绑定进入、离开、点击三个事件时导致背景色变化的切换。
现在以表格为例说明:表格背景色为默认的白色,当鼠标悬停第一行的时候背景色为黄色,鼠标离开的时候恢复白色。当鼠标点击第一行的时候,背景色变为红色,此时鼠标悬停和离开第一行的时候,背景色依然是红色,例如再点击第二行的时候,第二行变为红色,第一行为默认白色。
可参考实例:http://www.miniui.com/demo/#s...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多个事件触发</title>
<script src="jquery.js"></script>
<style>
table{
border:1px solid #000;border-collapse: collapse;width:500px;
}
td{border:1px solid #000;width:100%; height:30px;}
</style>
</head>
<body>
<table>
<tbody>
<tr> <td>11</td> </tr>
<tr> <td>21</td> </tr>
<tr> <td>31</td> </tr>
</tbody>
</table>
<script>
$("table").find("tr").on("mouseenter",function(){
$(this).css("background-color","yellow");
});
$("table").find("tr").on("mouseleave",function(){
$(this).css("background-color","#fff");
});
$("table").find("tr").on("click",function(){
$(this).css("background-color","red");
});
</script>
</body>
</html>
自己有尝试过鼠标进入事件的时候,事先判断此行的颜色,但是当鼠标来回移动,进入、离开事件触发多次的时候就不管用了。求大神解答~~~谢谢了
解决方案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多个事件触发</title>
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style>
table{
border:1px solid #000;border-collapse: collapse;width:500px;
}
td{border:1px solid #000;width:100%; height:30px;}
.red {
background-color: red!important;
}
.yellow {
background-color: yellow;
}
.white {
background-color: #fff
}
</style>
</head>
<body>
<table>
<tbody>
<tr> <td>11</td> </tr>
<tr> <td>21</td> </tr>
<tr> <td>31</td> </tr>
</tbody>
</table>
<script>
$(document).on("mouseenter", "table tr" ,function(){
$(this).removeClass("white").addClass("yellow");
}).on("mouseleave", "table tr",function(){
$(this).removeClass("yellow").addClass("white");
}).on("click", "table tr", function(){
$(this).addClass("red").siblings().removeClass("red");
});
</script>
</body>
</html>
这篇关于javascript - 一个元素绑定多个事件相互冲突的问题怎么解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文