更改悬停图像上的文字

时间:2013-02-11 00:35:30

标签: javascript jquery css hover

我有以下HTML代码:

<div id="container">
<ul>
<li><img src="#" /></li>
<li><img src="#" /></li>
</ul>
<h2>Some Text</h2>
</div>

我想要的只是将其中一个图像悬停在ul中,从而更改h2字段中的文本。如果用jQuery,javascript或css完成它并不重要,但它应该尽可能简单。

请用评论解释您的代码,以便我理解它!

谢谢!

3 个答案:

答案 0 :(得分:1)

好的,jquery很容易做到这一点:

//mouseover any li tag and do the following
$("img").hover(function(){
     //get the html code in teh li
     var text = $(this).attr("src");
     //put that in any or all h2 tags
     $("h2").text(text);
});


$("img").mouseout(function(){
     $("h2").html("");        
});

答案 1 :(得分:0)

您可以使用jQuery中的hover()函数来检测用户何时悬停在img上:

$('ul li img').hover(function() {
   $('h2').text('Some more text'); // set whatever text you want here
});

jsFiddle:http://jsfiddle.net/ZLtqQ/

答案 2 :(得分:0)

我认为这可以解决您的问题。

$("#container").find("img").each(function(){  //look for each img inside the #container div
  $(this).mouseover(function(){ // and when the mouse is over it
     $("h2").html($(this).attr("src")); // put the img source as h2 text
  })
})

提示:在h2上放置一个id,这样脚本就会将值放在你想要的h2中,享受:)