我有以下代码片段(由@SpencerWieczorek进行了调整,谢谢):



$('.parent').mouseenter(function(){
  $('.child').fadeToggle();
});

* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 500px;
  margin: 10px 10px;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 500px;
  height: 100%;
  display: block;
  overflow: hidden;
}


p {
  padding: 1em;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<img src="http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg" alt="" width="500px" height="auto" />

<div class="child">
<img src="http://maui.hawaii.edu/tlc/wp-content/uploads/sites/53/2013/11/testing.jpg" alt="" width="500px" height="auto" />
</div>
</div>





最终目标是运行多个实例,并使用同一页面中的OnMouseEnter事件对不同的元素进行操作。

我在考虑解决方案,但不确定是否可以更改父母/子女条款。是否可以定义多个父/子参数(例如,parent,parent1,parent2等,也可以是child,child1,child2等)?

最佳答案

您可以从当前元素使用".child"访问$(this).find('.child')。这样,它可以与其中的几个一起使用:

$('.parent').mouseenter(function(){
  $(this).find('.child').fadeToggle();
});




$('.parent').mouseenter(function(){
  $(this).find('.child').fadeToggle();
});

* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 500px;
  margin: 10px 10px;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 500px;
  height: 100%;
  display: block;
  overflow: hidden;
}


p {
  padding: 1em;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="parent">
<img src="http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg" alt="" width="500px" height="auto" />

<div class="child">
<img src="http://maui.hawaii.edu/tlc/wp-content/uploads/sites/53/2013/11/testing.jpg" alt="" width="500px" height="auto" />
</div>
</div>

<div class="parent">
<img src="http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg" alt="" width="500px" height="auto" />

<div class="child">
<img src="http://maui.hawaii.edu/tlc/wp-content/uploads/sites/53/2013/11/testing.jpg" alt="" width="500px" height="auto" />
</div>
</div>

关于javascript - 同一页面中的不同OnMouseEnter事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34474827/

10-12 13:05