在悬停

时间:2018-05-19 10:49:29

标签: javascript html css

我想在#switch元素悬停后让.content显示,并使#caption消失。

与元素ID建议类似,#switch元素应替换悬停时的标题。我使用Javascript来解决这个问题,但onmouseoveronmouseout函数无法与.content#caption一起使用,而#switch在悬停时突然转移。



document.getElementById('caption').onmouseover = function() {
  displaySwitch()
};
document.getElementById('switch').onmouseout = function() {
  hideSwitch()
};

function displaySwitch() {
  document.getElementById('caption').style.display = "none";
  document.getElementById('switch').style.display = "inline-block";
}

function hideSwitch() {
  document.getElementById('switch').style.display = "none";
  document.getElementById('caption').style.display = "block";
}

body {
  margin: 50px;
}

.content {
  height: 500px;
  width: 100%;
  border: 3px solid black;
}

#caption {
  font-size: 3em;
}

#switch {
  /* The element is hidden in advance. */
  display: none;
}

<div class="content">
  <a id="caption">Lorem Ipsum</a>

  <div id="switch">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ornare libero et vestibulum pellentesque. In accumsan et est dapibus viverra.</p>
  </div>

</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

根据您的要求'在.content元素悬停后使#switch可见并使#caption消失',将新标识box添加到content元素。并将onmouseoveronmouseout事件绑定到box元素。

请验证输出,是根据您的要求还是我做了不同的事情?

document.getElementById('box').onmouseover = function() {
  displaySwitch()
};

document.getElementById('box').onmouseout = function() {
  hideSwitch()
};

function displaySwitch() {
  document.getElementById('caption').style.display = "none";
  document.getElementById('switch').style.display = "inline-block";
}

function hideSwitch() {
  document.getElementById('switch').style.display = "none";
  document.getElementById('caption').style.display = "block";
}
body {
  margin: 50px;
}

.content {
  height: 500px;
  width: 100%;
  border: 3px solid black;
}

#caption {
  font-size: 3em;
}

#switch {
  /* The element is hidden in advance. */
  display: none;
}
<div class="content" id="box">
  <a id="caption">Lorem Ipsum</a>

  <div id="switch">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ornare libero et vestibulum pellentesque. In accumsan et est dapibus viverra.</p>
  </div>

</div>