ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaScript-将函数应用于具有相同类名的div集合中的特定div

2019-11-11 08:39:06  阅读:265  来源: 互联网

标签:hover css html javascript jquery


当我将鼠标悬停在.winner-container上时,JS函数告诉.headline从.winner-container中移出,然后告诉.bottom移入.winner-container.当我将鼠标悬停时,情况正好相反.

问题是,我将拥有数百个带有.winner-container类的容器.因此,我意识到,当我将鼠标悬停在一个容器上时,该功能将同时应用于数百个不同的容器.我只希望将函数应用于我悬停的特定容器.我可以通过为每个容器指定一个ID,然后为每个ID编写新的JS代码来做到这一点,但是考虑到会有300个这样的div,这将需要大量的工作.有没有更优雅的解决方案?

https://jsfiddle.net/6sm6ajht/

的HTML

<div class="winner-container">
  <div class="top">
    <h4 class="headline">SME Example 1</h4>
  </div>
  <div class="bottom">
    <div class="winner-words">
      <h6>SME Examle 1 is a technology company.</h6>
      <h6><a>Learn more...</a></h6>
    </div>
  </div>
</div>

<div class="winner-container">
  <div class="top">
    <h4 class="headline">SME Example 2</h4>
  </div>
  <div class="bottom">
    <div class="winner-words">
      <h6>SME Examle 2 is an e-commerce company.</h6>
      <h6><a>Learn more...</a></h6>
    </div>
  </div>
</div>

的CSS

.winner-container {
  position: relative;
  box-shadow: 0px 2.5px 1px 0px rgba(0, 0, 0, 0.25);
  border: 1px solid #074E68;
}

.winner-container,
.top,
.bottom {
  width: 10em;
  height: 12em;
  overflow: hidden;
}

.bottom {
  position: absolute;
  height: 12em;
  width: 100%;
  top: 12em;
  transition: 0.5s ease-in-out;
}

.top .headline {
  position: absolute;
  top: 2.5em;
  width: 100%;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0px 1px 1px 2px rgba(0, 0, 0, 0.1);
  transition: 0.5s ease-in-out;
}

.top-up .headline {
  top: -2.5em;
}

.bottom-up.bottom {
  top: 0em;
  background-color: rgba(0, 0, 0, 0.65);
}

的JavaScript

$(".winner-container").on("mouseenter", function() {
  $(".top").addClass('top-up');
  $(".bottom").addClass('bottom-up');
});

$(".winner-container").on("mouseleave", function() {
  $(".top").removeClass('top-up');
  $(".bottom").removeClass('bottom-up');
});

解决方法:

对于$(this)选择器来说,这是一个绝佳的机会.因为有许多相同的元素,但是您只希望每个事件处理程序都引用该特定元素,所以可以使用$(this)并使用.children之类的相对选择器来定位相对于this元素的其他元素.

JSfiddle

$(".winner-container").on("mouseenter", function() {
  $(this).children(".top").addClass('top-up');
  $(this).children(".bottom").addClass('bottom-up');
});

$(".winner-container").on("mouseleave", function() {
  $(this).children(".top").removeClass('top-up');
  $(this).children(".bottom").removeClass('bottom-up');
});

标签:hover,css,html,javascript,jquery
来源: https://codeday.me/bug/20191111/2018601.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有