本文介绍了如何使用JQuery/Javascript更改悬停时div的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery将鼠标悬停在div上时,我正在尝试更改它的内容.我已经看到了堆栈溢出的答案,但似乎无法正常工作.

I'm trying to change the contents of a div when it's hovered over using JQuery. I've seen answers on stack overflow, but I can't seem to get it working.

我尝试过

$( "imgDiv" ).mouseover(
    function() {
        $("tdiv").textContent = "hovering";
    },
    function() {
        $("tdiv").textContent = 'title';
    }
);

我也将"mouseover"替换为"hover".我使用了一个变量和实际的div来代替"imgDiv".

I've also replaced "mouseover" with "hover". I've used a variable and the actual div in place of "imgDiv".

这是我的代码的样子:

imgDiv = document.getElementById('imgDiv');
tDiv = document.getElementById('titleDiv');


$( "imgDiv" ).mouseover(
			  function() {
			      $("tdiv").textContent = "hovering";
			  }, function() {
			    $("tdiv").textContent = 'title';
			  }
			);
body {
  background: white;
  padding: 20px;
  font-family: Helvetica;
}
#imgDiv {
  width: 100px;
  height: 100px;
  background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">

<div id=titleDiv>title</div>

</div>

推荐答案

您可以将jQuery的.hover()函数与.text()函数一起使用来执行所需的操作.另外,无需document.getElementById:

You can use jQuery's .hover() function along with the .text() function to do what you want. Also, no need for document.getElementById:

$("#imgDiv").hover(
  function() {
    $("#titleDiv").text("hovering");
  },
  function() {
    $("#titleDiv").text('title');
  }
);
body {
  background: white;
  padding: 20px;
  font-family: Helvetica;
}

#imgDiv {
  width: 100px;
  height: 100px;
  background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
  <div id="titleDiv">title</div>
</div>

这篇关于如何使用JQuery/Javascript更改悬停时div的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 06:02