悬停更改背景div

时间:2019-03-15 09:18:11

标签: javascript html css

我想使用JavaScript来更改悬停时div的背景和文本。但是我有一些问题。这是代码:

.square1 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: black;
  color: white;
}

.square2 {
  margin-top: 20px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: blue;
  color: white;
}
<div class="squares">
  <div class="square1">
    <p>I'm square1!</p>
  </div>

  <div class="square2">
    <p>I'm square2!</p>
  </div>
</div>

我最后要做的是使第一个正方形在悬停时显示为第二个正方形。有人可以帮我吗?

4 个答案:

答案 0 :(得分:0)

.square1 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: black;
  color: white;
}

.square1:hover {
  margin-top: 20px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: blue;
  color: white;
}

.square2 {
  margin-top: 20px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: blue;
  color: white;
}

.square2:hover {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: black;
  color: white;
}
<div class="squares">
  <div class="square1">
    <p>I'm square1!</p>
  </div>

  <div class="square2">
    <p>I'm square2!</p>
  </div>
</div>

答案 1 :(得分:0)

这就是您所需要的:

.square1:hover {
      background:blue;
      color:white;
      /* or any other props*/
}

答案 2 :(得分:0)

var w;
function a(e)
{
w=e.textContent;
e.textContent=document.querySelector('.square2 > p').textContent

}
function b(e)
{
e.textContent=w
}
.square1 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: black;
  color: white;
}

.square1:hover {
  margin-top: 20px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: blue;
  color: white;
}

.square2 {
  margin-top: 20px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: blue;
  color: white;
}

.square2:hover {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: black;
  color: white;
}
<div class="squares">
  <div class="square1" onmouseover='a(this)' onmouseout='b(this)'>
    <p>I'm square1!</p>
  </div>

  <div class="square2">
    <p>I'm square2!</p>
  </div>
</div>

答案 3 :(得分:0)

Prince Maheer Ali 所述;如果想让它具有更好的淡入淡出效果,请添加到CSS中:

-webkit-transition: all .3s ease;
-moz-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;