2013-05-28 41 views
1

我有一个包含图像的div,我想在小工具上显示所有内部图像的标题。如何显示所有div的内部图像标题onmouseover?

所以,我有这样的事情:

<div id=MyDiv onmouseover="highlight(this);"> 

而且我的javascript:

function highlight(element) {  

     for (var i = 0; i < element.children.length; i++) { 
      if (element.children[i].tagName == "IMG") 
       element.children[i].title.show(); 
     } 
    } 

但我得到一个消息 - 对象 “X” 有没有方法秀。

+0

没有jQuery的? –

回答

1

下面是使用jQuery的例子:

HTML:

<div id="MyDiv"> 
    <img src="http://chandra.harvard.edu/photo/2012/m101/m101_xray_thm100.jpg" title="img1" /> 
    <img src="http://passport-cdn.mobilenations.com/avatars/000/004/072/100x100_4072871.jpg?r=1" title="img2" /> 
</div> 

的jQuery:

$("#MyDiv").mouseenter(function() { 
    $mydiv = $(this); 
    $.each($('img', $mydiv), function() { 
     var pos = $(this).position(); 
     $('<div>', { 
      class: 'imgtitle' 
     }).css({ 
      position: 'absolute', 
      color: 'red', 
      top: pos.top + 5, 
      left: pos.left + 5 
     }) 
     .html($(this).attr('title')) 
     .insertAfter($(this)); 
    }); 
}).mouseleave(function() { 
    $('.imgtitle').remove(); 
}); 

这里有一个的jsfiddle显示它在行动:http://jsfiddle.net/obryckim/k5hcJ/

2

您正在使用纯JavaScript。 title是一个字符串,正如消息所示,它没有方法show

如果你想要做什么是警报在弹出所有的标题,你可以这样做:

function highlight(element) {  

     for (var i = 0; i < element.children.length; i++) { 
      if (element.children[i].tagName == "IMG") 
       alert(element.children[i].title); 
     } 
    } 

如果,另一方面,你想向他们展示你的页面上,你需要的东西像这样:

function highlight(element) {  
     var outputelement = document.getElementById("idofsomeelementyouhaveonyourpage"); 
     for (var i = 0; i < element.children.length; i++) { 
      if (element.children[i].tagName == "IMG") 
       outputelement.innerHTML += element.children[i].title; 
     } 
    } 

当然,用第二种方法,你需要一个onmouseout处理器隐藏的标题为好。