将鼠标悬停在一个框上并突出显示另

时间:2017-01-24 13:01:11

标签: html css

.first {
  background: red;
  width: 100px;
  height: 100px;
}
.first:hover .outer-box {
  background: black;
}
.outer-box {
  width: 100px;
  height: 100px;
  background: green;
}
<div class="icons">
  <div class="first"></div>
</div>

<div class="outer-box"></div>

如何将鼠标悬停在一个框上并突出显示另一个框?

如果盒子在同一个容器中,但不幸的是它们不是那么容易。

Hope you can help perhaps updating my pen with no jquery if doable

4 个答案:

答案 0 :(得分:2)

您无法操纵没有层次结构级别的对象。您可以使用此方法:

width

或者您可以使用javascript:

<div class="icons">
   <div class="first">
       <div class="outer-box"> </div>
   </div>
</div>

/* css */
.first:hover .outer-box{
    /* Your css code */
}
document.getElementsByClassName('first')[0].onmouseover = function(){
  document.getElementsByClassName('outer-box')[0].style = "background: black"
}

document.getElementsByClassName('first')[0].onmouseout = function(){
  document.getElementsByClassName('outer-box')[0].style = "background: green"
}
.first{
  background: red;
  width: 100px;
  height: 100px;
}

.outer-box{
  width: 100px;
  height: 100px;
  background: green;
}

答案 1 :(得分:2)

您可以使用+ combinator 轻松完成此操作。事实是,它需要是一个相对对象,意思是 - 它必须在html层次结构中处于同一级别。

您可以详细了解此选择器 here.

Here is an update Pen.

答案 2 :(得分:0)

这是一个使用最少量javascript的简单方法。

&#13;
&#13;
function color() {
  document.getElementById("outer").style.background = "black";
}
function outcolor() {
  document.getElementById("outer").style.background = "green";
}
&#13;
.first{
  background: red;
  width: 100px;
  height: 100px;
}

.outer-box{
  width: 100px;
  height: 100px;
  background: green;
}
&#13;
<div class="icons">
  <div class="first" onmouseover="color()" onmouseout="outcolor()">
  </div>
</div>

<div class="outer-box" id="outer">
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

将class =“ show someid”添加到项目中,将其悬停时,它将突出显示someid,或者仅添加class =“ show”,则将突出显示可悬停对象的innerText中的元素。

var show=document.getElementsByClassName('show')
for(var i=0;i<show.length;i=i+1){
 show[i].onmouseover = function(){
  var theclass=this.getAttribute('class');
  theclass=theclass.replace("show","");
  theclass=theclass.replace(" ","");
  if(theclass==''){
   var text=this.innerText;
  } else {
   var text=theclass;
  }
  document.getElementById(text).style = "background: #dddddd;"
 }
 show[i].onmouseout = function(){
  var theclass=this.getAttribute('class');
  theclass=theclass.replace("show","");
  theclass=theclass.replace(" ","");
  if(theclass==''){
   var text=this.innerText;
  } else {
   var text=theclass;
  }
  document.getElementById(text).style = "background: none;"
 }
}
<p id="item1">This is item 1.</p>
<p id="item2">This is item 2.</p>
<hr>
<span class="show">item1</span>
<br>
<span class="show item2">Hover me to show item 2</span>