您的位置:首页 > Web前端 > CSS

获取图片的路径,即src的值,并依据不同的样式在alt属性中显示

2011-05-16 22:15 435 查看
 

刘大伟

2011.05.09

浏览网页中图片的时候,根据网页的易用性要求,当鼠标放到图片上的时候需要显示该图片的相关信息,大多数情况下显示的都是该图片的名称,为了自动获取每一张图片的名称可以在js脚本中通过获取该图片的src的值实现。不过由于默认情况下,alt显示出来的效果,如字体、颜色、背景等等,并不尽人意,因此样式需要自己设计,这些也可以在脚本中实现。根据网上已有的一些方法,整理出以下的代码可以简单的实现这种功能:

<SCRIPT LANGUAGE="JavaScript">
function getAbsolutePosition(obj)

{
    position = new Object();
    position.x = 0;
   
position.y = 0;
    var tempobj = obj;
    while(tempobj!=null
&& tempobj!=document.body)
    {
       
if(window.navigator.userAgent.indexOf("MSIE")!=-1)
        {
           
position.x += tempobj.offsetLeft;
            position.y +=
tempobj.offsetTop;
        }
        else
if(window.navigator.userAgent.indexOf("Firefox")!=-1)
        {

            position.x += tempobj.offsetLeft;
            position.y +=
tempobj.offsetTop;
        }
        tempobj = tempobj.offsetParent

    }
    return position;
}
function showalt(e,s)
{
   
var object = document.getElementById(s);//s为img的ID
    var m =
object.getAttribute('src', 2);//如果第二个参数为2,则显示的内容为绝对路径,和下面被注释行的结果一样
    //var
m=document.getElementById(s).src;
    e = e || window.event
    var obj
= e.target||e.srcElement
    var pos = getAbsolutePosition(obj)
    var
div = document.getElementById("imgalt")
    div.style.display=""
   
div.style.top = pos.y+e.offsetY+10+"px"
    div.style.left =
pos.x+e.offsetX+10+"px"
    div.innerHTML = m;
    window.status =
e.clientY
}
function hide()
{
   
document.getElementById("imgalt").style.display="none"
}
</SCRIPT>

<img id="id1" src="pic1.jpg" width=50 onmousemove="showalt(event,'id1')"
onmouseout="hide()">
<img id="id2" src="pic2.jpg" width=150
onmousemove="showalt(event,'id2')"onmouseout="hide()">
<div id=imgalt
style="position:absolute;border:1px solid
black;background-color:yellow;display:none"></div>

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐