jquery - 在将鼠标悬停在某些内容上的同时,替换内容

标签 jquery html css mouseover

虽然悬停内容发生了变化,但是当我移除悬停时旧内容没有被替换。

$('div.animalcontent').hide();
$('div').hide();
$('p.animal').bind('mouseover', function() {
  $('p.animal').hide();
  $('div.animalcontent').fadeOut();
  $('#' + $(this).attr('id') + 'content').fadeIn();
});
.animalcontent {
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<p class='animal' id='dog'>dog url</p>
<div id='dogcontent' class='animalcontent'>Doggiecontent!</div>

有人知道怎么走吗?

最佳答案

首先,jQuery 1.5.2 已经超过 7 年了。你应该立即升级它,最好升级到 v3 分支上的东西。

您的问题是因为您没有控制 mouseleave 事件的逻辑来替换您淡入/淡出的内容的状态。

也就是说,您根本不需要 JS,因为 CSS 更适合此任务,因为它消除了对 JS(可能被禁用)的依赖,而且它的性能也更好。

您可以使用 :hover 伪选择器和 transition 规则来执行淡入淡出。像这样:

.hover-toggle-container { 
  position: relative;
  height: 1.5em;
}
.hover-toggle-container > div {
  position: absolute;
  transition: opacity 0.3s; 
}

.hover-toggle-container .primary { opacity: 1; }
.hover-toggle-container .secondary { opacity: 0; }

.hover-toggle-container:hover .primary { opacity: 0; }
.hover-toggle-container:hover .secondary { opacity: 1; }
<div class="hover-toggle-container">
  <div class="primary">dog url</div>
  <div class="secondary">Doggiecontent!</div>
</div>

<div class="hover-toggle-container">
  <div class="primary">Foo</div>
  <div class="secondary">Bar</div>
</div>

请注意,此逻辑也是 DRY 的,可用于多个 .hover-toggle-container 元素,如上面的演示所示。

关于jquery - 在将鼠标悬停在某些内容上的同时,替换内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49530263/

相关文章:

javascript - 当它被拖到另一个 div 附近时淡出 div

javascript - 基于 PHP 的大数据集表单自动完成

javascript - 使用 chrome 扩展时访问 CSS 中的本地存储?

html - 如何在水平线而不是垂直行中显示社交媒体图标

javascript - 当我调整浏览器窗口大小时,我的图像在它们应该保持在一起时移动了

jquery - 我想在 jquery 中使用 children 方法为所有子 div 设置样式

javascript - jQuery UI 可排序 : Move clone but keep original

caching - HTML5 应用程序缓存与浏览器缓存

css - Bootstrap 静态布局 "visual"左右排水沟 firefox chrome

html - :hover to stay active when cursor over dropdown