将鼠标移到元素内的文本上(文本放置在单独的 div 中)会以非常快的 mouseenter 重复触发,但您希望它只触发一次,即在不对子元素做出反应的情况下进入方形块时触发。
JavaScript 代码:
$('.square').mouseenter(function (){
var color = colorGenerator();
(this).style.backgroundColor=color;
$(this).children('.text').remove();
$('<div>').addClass('text').appendTo(this).text(color);
CSS 代码:
.square {
width: 100px; height: 100px;
float:left;
background-color: white;
color:white;
text-align: center;
font-size:20px;
display: table;
}
.text{
text-align: center;
display: table-cell;
vertical-align: middle;
}
.square:hover {
box-shadow: 0px 0px 20px #F0FFF0 inset;
text-align: center;
vertical-align: middle;
color:white;
}
HTML 代码:
<div class="container">
<div class="title-text">RANDOM COLOR</div>
<div class="workspace">
<div class="square">
<div class="text"></div>
</div>
</div>
</div>
尽管事件有奇怪的行为,因此应该从处理中排除子元素:
解决方案: