悬停元素影响另一个div内的另一个

时间:2015-10-20 22:29:42

标签: css hover element

我有以下代码,我想这样做:当<li> <a href="#" class="userPicture"></a> <div class="contentNew"> <div class="date">17 Jul</div> <div class="description"> <a href="#" class="name">Jose</a> published a product </div> </div> </li> 悬停时,类名应该改变。我该怎么做?

foreach (var p in Player.GroupBy(x => x).Select(x => new { Player = x.Key, Count = x.Count()}))
            Console.WriteLine("Player {0} occurs {1} time{2}", p.Player, p.Count, p.Count == 1 ? "s" : "");

2 个答案:

答案 0 :(得分:0)

这取决于你需要达到的目标。如果您只想在鼠标悬停上设置样式元素,那么使用它会更好:hover css selector。 但如果您需要一些额外的逻辑,则需要使用javascript。

可以这样做:

 <li>
       <a href="#" class="userPicture" onmouseover="this.setAttribute('class', 'userPicture-hovered');" onmouseleave="this.setAttribute('class', 'userPicture');"></a>
          <div class="contentNew">
            <div class="date">17 Jul</div>
            <div class="description">
                <a href="#" class="name">Jose</a> published a product
            </div>
          </div>
 </li>

内联javascript示例:https://jsfiddle.net/rw9dcg5d/

css :hover示例:https://jsfiddle.net/539wep5g/

答案 1 :(得分:0)

如果您确实需要更改类名,可以使用javascript完成。但正如@Yura Yakym所提到的,css:hover可能是一种更好的方法。

&#13;
&#13;
var a = document.querySelectorAll(".userPicture");
for (var i = 0; i < a.length; i++) {
  var defaultClassName = a[i].className;
  a[i].addEventListener("mouseover", function() {
    this.className = "userPicture-hover"
  });
  a[i].addEventListener("mouseout", function() {
    this.className = defaultClassName
  });
}
&#13;
.userPicture-hover {
  background: #c00;
}
&#13;
<ul>
  <li>
    <a href="#" class="userPicture">User picture</a>
    <div class="contentNew">
      <div class="date">17 Jul</div>
      <div class="description">
        <a href="#" class="name">Jose</a> published a product
      </div>
    </div>
  </li>
  <li>
    <a href="#" class="userPicture">User picture</a>
    <div class="contentNew">
      <div class="date">17 Jul</div>
      <div class="description">
        <a href="#" class="name">Jose</a> published a product
      </div>
    </div>
  </li>
</ul>
&#13;
&#13;
&#13;