onmouseover就像一个onclick,而不是一个悬停

时间:2016-03-28 09:02:52

标签: javascript jquery html onmouseover onmouseout

我有一张“卡片”表,每次鼠标通过卡片时,我想在卡片顶部显示说明。为此,我正在尝试使用onmouseover和onmouseout函数。

我的Javascript:

function showDescription(obj) {
  elem1 = document.getElementById(obj + '_1');
  elem1.style.display = 'none';

  elem2 = document.getElementById(obj + '_2');
  elem2.style.display = 'block';
}

function hideDescription(obj) {
  elem1 = document.getElementById(obj + '_1');
  elem1.style.display = 'block';

  elem2 = document.getElementById(obj + '_2');
  elem2.style.display = 'none';
}

我的HTML:

<table id='teamTable' align="center">
  <tr>
    <td onmouseover="showDescription('content_1')" onmouseout="hideDescription('content_1')">
      <div id="content_1_1" class="teamTableTitle">
        Name
      </div>
      <div id="content_1_2" class="teamTableDescription">
        Description
      </div>
    </td>
  </tr>
</table>

Fiddle Link

问题是我的两个事件onmouseover和onmouseout就像是在onclick上。鼠标通过卡片没有任何反应,但是当我点击...

时它会起作用

任何人都知道我做错了什么? :/

2 个答案:

答案 0 :(得分:0)

基于我对您的代码的理解。我想出了这个并将其转换为jQuery

HTML

<table id='teamTable' align="center">
     <tr>
        <td id="content_1">
            <div id="content_1_1" class="teamTableTitle">
                 Name (Hover me to show description)
            </div>
            <div id="content_1_2" class="teamTableDescription">
                 Description
            </div>
        </td>
     </tr>
</table>

JS(jQuery)

$('#content_1').hover(function(){
    $(this).find('div').eq(0).hide().next('div').show();
},function(){
    $(this).find('div').eq(0).show().next('div').hide();
});

Click this for working JSFiddle

答案 1 :(得分:0)

这是针对您的问题的无jQuery解决方案:

<强> HTML

<table id='teamTable' align="center">
  <tr>
    <td class="td-test">
      <div id="content_1_1" class="teamTableTitle">
        Name
      </div>
      <div id="content_1_2" class="teamTableDescription">
        Description
      </div>
    </td>
  </tr>
</table>

<强>的Javascript

var tableEl = document.getElementsByClassName('td-test');

tableEl[0].addEventListener("mouseover", showDescription, false);
tableEl[0].addEventListener("mouseout", hideDescription, false);

function showDescription() {
  var el1 = this.querySelector("#content_1_1");
  var el2 = this.querySelector("#content_1_2");

  el1.style.display = "none";
  el2.style.display = "block";
}

function hideDescription() {
  var el1 = this.querySelector("#content_1_1");
  var el2 = this.querySelector("#content_1_2");

  el1.style.display = 'block';
  el2.style.display = 'none';
}