29

下面的 HTML:

<div id="category">

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

</div>

当鼠标悬停在 div 的内容上时,它是 backgroundColor 和 h2(在这个 div 内) backgroundColor 改变(就像 CSS:悬停)

我知道这可以使用 CSS (: hover) 在现代浏览器中执行此操作,但 IE6 不起作用。

如何使用 JavaScript(不是 jQuery 或其他 JS 框架)来做到这一点?

编辑:如何也改变 h2 backgroundColor

4

9 回答 9

62
var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};
于 2009-12-09T15:20:35.307 回答
10

在代码中添加/更改元素的样式是一种不好的做法。今天你想改变背景颜色,明天你想改变背景图像,明天之后你决定改变边框也很好。

每次只因为设计需求发生变化而编辑代码是一件痛苦的事。此外,如果你的项目会增长,更改 js 文件将更加痛苦。更多的代码,更多的痛苦。

尽量避免使用硬编码样式,这将节省您的时间,如果您做得对,您可以要求为其他人执行“更改颜色”任务。

因此,您可以在节点上添加/删除 CSS 类,而不是更改样式的直接属性。在您的特定情况下,您只需对父节点执行此操作 - “div”,然后通过 CSS 设置子节点的样式。所以不需要对 DIV 和 H2 应用特定的样式属性。

再推荐一点。尽量不要连接硬编码的节点,而是使用一些语义来做到这一点。例如:“将事件添加到具有类‘内容’的所有节点。

总之,这是我将用于此类任务的代码:

//for adding a css class
function onOver(node){
   node.className = node.className + ' Hover';
}

//for removing a css class
function onOut(node){
    node.className = node.className.replace('Hover','');
}

function connect(node,event,fnc){
    if(node.addEventListener){
        node.addEventListener(event.substring(2,event.length),function(){
            fnc(node);
        },false);
    }else if(node.attachEvent){
        node.attachEvent(event,function(){
            fnc(node);
        });
    }
}

// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
    if(div.className.match('content')){
        connect(div,'onmouseover',onOver);
        connect(div,'onmouseout',onOut);
    }
}

你的 CSS 应该是这样的:

.content {
    background-color: blue;
}

.content.Hover{
    background-color: red;
}

.content.Hover h2{
    background-color : yellow;
}
于 2009-12-09T16:20:19.950 回答
5

通过 DOM 访问要更改的元素,例如在事件处理程序中使用document.getElementById()或通过this,然后更改该元素中的样式:

document.getElementById("MyHeader").style.backgroundColor='red';

编辑

您也可以使用getElementsByTagName,(未经测试)示例:

function colorElementAndH2(elem, colorElem, colorH2) {
    // change element background color
    elem.style.backgroundColor = colorElem;
    // color first contained h2
    var h2s = elem.getElementsByTagName("h2");
    if (h2s.length > 0)
    {
        hs2[0].style.backgroundColor = colorH2;
    }
}

// add event handlers when complete document has been loaded
window.onload = function() {
    // add to _all_ divs (not sure if this is what you want though)
    var elems = document.getElementsByTagName("div");
    for(i = 0; i < elems.length; ++i)
    {
        elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
        elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
    }
}
于 2009-12-09T15:21:01.550 回答
3
<script type="text/javascript">
 function enter(elem){
     elem.style.backgroundColor = '#FF0000';
 }

 function leave(elem){
     elem.style.backgroundColor = '#FFFFFF';
 }
</script>
 <div onmouseover="enter(this)" onmouseout="leave(this)">
       Some Text
 </div>
于 2009-12-09T15:21:48.937 回答
2

非常简单,只需在 javaScript 上使用一个函数并在点击时调用它

   <script type="text/javascript">
            function change()
            {
            document.getElementById("catestory").style.backgroundColor="#666666";
            }
            </script>

    <a href="#" onclick="change()">Change Bacckground Color</a>
于 2016-06-15T13:51:39.643 回答
1

这可能有点奇怪,因为我真的不是一个认真的程序员,而且我正在以发明青霉素的方式在编程中发现一些东西——纯属偶然。那么如何在鼠标悬停时更改元素?:hover就像使用a元素一样使用属性。

例子:

div.classname:hover
{
    background-color: black;
}

这将更改任何divclassname以在鼠标悬停上具有黑色背景。您基本上可以更改任何属性。在 IE 和 Firefox 中测试

快乐编程!

于 2010-10-14T23:16:46.553 回答
0

要在没有 jQuery 或任何其他库的情况下执行此操作,您需要将 onMouseOver 和 onMouseOut 事件附加到每个 div 并更改事件处理程序中的样式。

例如:

var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
    if (child.nodeType == 1 && child.className == "content") {
        child.onmouseover = function() {
            this.style.backgroundColor = "#FF0000";
        }

        child.onmouseout = function() {
            // Set to transparent to let the original background show through.
            this.style.backgroundColor = "transparent"; 
        }
    }
}

如果您的 h2 没有设置自己的背景,则 div 背景也会显示出来并为其着色。

于 2009-12-09T15:21:16.317 回答
0

如果您愿意将非语义节点插入到您的文档中,您可以通过将您的 div 包装在虚假的 A 标签中,以仅 CSS IE 兼容的方式执行此操作。

<style type="text/css">
  .content {
    background: #ccc;
  }

  .fakeLink { /* This is to make the link not look like one */
    cursor: default;
    text-decoration: none;
    color: #000;
  }

  a.fakeLink:hover .content {
    background: #000;
    color: #fff;
  }

</style>
<div id="catestory">

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

</div>
于 2009-12-09T15:32:48.953 回答
0

你可以试试这个脚本。:)

    <html>
    <head>
    <title>Div BG color</title>
    <script type="text/javascript">
    function Off(idecko)
    {
    document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
    }
    function cOn(idecko)
    {
    document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
    }
    function hOn(idecko)
    {
    document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
    }
    </script>
    </head>
    <body>

    <div id="catestory">

        <div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
          <h2 id="h21">some title here</h2>
          <p>some content here</p>
        </div>

        <div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
          <h2 id="h22">some title here</h2>
          <p>some content here</p>
        </div>

        <div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
          <h2 id="h23">some title here</h2>
          <p>some content here</p>
        </div>

    </div>

    </body>
<html>
于 2013-02-13T15:25:03.990 回答