문제

아래 HTML :

<div id="catestory">

  <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의 내용을 마우스로드하면 배경 컬러와 H2 (이 div 내부) 배경 검색기 변경 (CSS : 호버)입니다.

나는 이것이 CSS (: 호버)를 사용하여 최신 브라우저에서이를 수행 할 수 있지만 IE6은 작동하지 않습니다.

JavaScript (jQuery 또는 기타 JS 프레임 워크가 아님)를 사용하여이를 수행하는 방법은 무엇입니까?

편집 : H2 배경 검색기를 변경하는 방법

도움이 되었습니까?

해결책

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';
};

다른 팁

코드에서 요소의 스타일을 추가/변경하는 것은 나쁜 연습입니다. 오늘은 배경을 바꾸고 싶습니다 색깔 그리고 내일 배경을 바꾸고 싶습니다 영상 그리고 내일 이후에 당신은 또한 변화하는 것이 좋을 것이라고 결정했습니다. 국경.

설계 요구 사항이 변경되기 때문에 매번 코드를 편집합니다. 또한 프로젝트가 커지면 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);
    }
}

그리고 당신은 다음과 같을 것입니다.

.content {
    background-color: blue;
}

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

.content.Hover h2{
    background-color : yellow;
}

예를 들어 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'); }
    }
}
<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>

나는 진지한 프로그래머가 아니기 때문에 페니실린이 발명되는 방식으로 프로그래밍 할 때 물건을 발견하고 있기 때문에 이것은 약간 이상 할 수 있습니다. 그렇다면 마우스 오버에서 요소를 변경하는 방법은 무엇입니까? 사용 :hover 그냥 좋아하는 속성 a 집단.

예시:

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

이것은 변경됩니다 div 수업과 함께 classname Mousover에 검은 배경을 갖기 위해. 기본적으로 모든 속성을 변경할 수 있습니다. IE 및 Firefox에서 테스트

행복한 프로그래밍!

디스크 인 노드를 문서에 삽입하려는 경우 DIV를 가짜 태그로 감싸서 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>

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 배경이 표시되어 색칠합니다.

이 스크립트를 시도 할 수 있습니다. :)

    <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>

매우 간단하다

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

    <a href="#" onclick="change()">Change Bacckground Color</a>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top