如何将CSS样式应用于div和嵌套在div中的div

时间:2016-12-05 21:04:35

标签: javascript html css

所以,基本上我在一些文本的顶部有框,当你将鼠标悬停在它上面时,它会向下移动,并隐藏文字:

<div id="box" onmouseover="tran1()" onmouseout="tran2()">
    <p id="par"><b>Hover Me.</b></p>
</div>

<p id="movealong">I will hide!</p>

这是脚本:

function tran1() {
    document.getElementById("par").innerHTML = "<b>Where'd he go?</b>";
}
function tran2() {
    document.getElementById("par").innerHTML = "<b>Hover Me.</b>";
}

最后是CSS让它失效:

#box {
    width:100px;
    height:95px;
    border:3px solid #000;
    border-radius: 8px;
    background-color:#06F;
    text-align:center;
}
#box:hover {
    width:100px;
    height:150px;
    border:3px solid #000;
    border-radius: 8px;
    background-color:#066;
}

但是,当我将鼠标悬停在文字上时,文字会更改为&#34;将鼠标悬停在&#34;上。如何同时拨打boxpar?是问题的CSS还是JS?

3 个答案:

答案 0 :(得分:0)

为什么使用JS代替文本更改?

&#13;
&#13;
function showHidden(el) {
  el.className += " showHidden";
}
function hideHidden(el) {
  el.className = "";
}
&#13;
.hidden {
  display: none;
  }

div.showHidden p {
    display: none;
  }

div.showHidden p.hidden {
    display: block;
  }
&#13;
<div onmouseover="showHidden(this)" onmouseout="hideHidden(this)"><p>Hover me</p><p class="hidden">Hide me</p></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

不确定您是否对JQuery解决方案感兴趣,但这就是解决问题的简单方法:

&#13;
&#13;
var $par = $('#par');
$('#box').hover(function() {
  // On mousein
  $par.html("Where'd he go?");
}, function() {
  // On mouseout
  $par.html('Hover Me.');
});
&#13;
#box {
  width: 100px;
  height: 95px;
  border: 3px solid #000;
  border-radius: 8px;
  background-color: #06F;
  text-align: center;
}
#box:hover {
  width: 100px;
  height: 150px;
  border: 3px solid #000;
  border-radius: 8px;
  background-color: #066;
}
&#13;
<div id="box">
  <p id="par"><b>Hover Me.</b></p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

使用#box:hover + P#movealong{隐藏元素

function tran1() {
    document.getElementById("par").innerHTML = "<b>Where'd he go?</b>";
}
function tran2() {
    document.getElementById("par").innerHTML = "<b>Hover Me.</b>";
}
#box {
    width:100px;
    height:95px;
    border:3px solid #000;
    border-radius: 8px;
    background-color:#06F;
    text-align:center;
}
#box:hover {
    width:100px;
    height:150px;
    border:3px solid #000;
    border-radius: 8px;
    background-color:#066;
}
#box:hover + P#movealong{
  display:none;
}
<div id="box" onmouseover="tran1()" onmouseout="tran2()">
    <p id="par"><b>Hover Me.</b></p>
</div>

<p id="movealong">I will hide!</p>