OnMouseEnter代码替代

时间:2015-09-22 21:44:42

标签: javascript jquery html css

我有这个代码片段最初是由Shomz制作的(特别感谢),但最近解决方案在Chrome中乱七八糟(淡入淡出效果有时会跳过) - 在v45.0.2454.99 m(64 -bit)以及v45.0.2454.85 m(64位),Win7 64位;

var shown = true;
var parent = document.querySelector('.parent');
var child = document.querySelector('.child');

parent.addEventListener('mouseenter', function(){
  child.style.opacity = shown ? 0 : 1;
  shown = !shown;
});
* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 100%;
  margin: 10px auto;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
  transition: opacity 0.5s linear;
}


p {
  padding: 1em;
}
<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>

代码应该像我们在this示例中那样工作。 此时,我对您的JS / jQuery / CSS代码替代感兴趣。是否有可能重写代码以便在最新版本的Chrome中运行?感谢。

2 个答案:

答案 0 :(得分:1)

事件onmouseenter可能是个问题。当你嵌套DOM时,这个事件比你想象的要多。在MDN上有一个很棒的文章,但快速解决方案是尝试onmouseover

答案 1 :(得分:1)

使用jQuery,您只需使用fadeToggle()

&#13;
&#13;
$('.parent').mouseenter(function(){
  $('.child').fadeToggle();
});
&#13;
* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 100%;
  margin: 10px auto;
  position: relative;
}

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


p {
  padding: 1em;
}
&#13;
<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>
&#13;
&#13;
&#13;