图片上的标题文字

时间:2014-01-14 17:52:42

标签: javascript html css

对不起,这是一个新手问题。我想显示从我的服务器目录中获取的随机图片,我想显示与每个图像相关的文本(同一目录中的txt文件。例如:1.jpg - > 1.txt; 2.jpg - > 2.txt ...)。我希望文本显示在图像上方,位于图像顶部的框架中,只有鼠标悬停在图像上时才会显示。

可在此处找到javascript代码,css和html代码:

http://jsfiddle.net/Totoleheros/ES22a/

html代码:

<img id="fullSize" onload="fixImage(this)" />
<div id="HOLDER">
<div id="theCaption"></div>
</div>
<img id="showImage" alt="random image" />

CSS代码:

/* The first style is to hide the text*/
#theCaption {
position: absolute;
width: 200px;
height: 331px;
filter:alpha(opacity=0);
-moz-opacity:0;
-khtml-opacity: 0;
opacity: 0;
z-index: 3;
}
/*The send style is to show the text on hover*/
#theCaption:hover, #theCaption:active {
position: absolute;
width: 200px;
height: 40px;
background-color: #eeeeee;
color: #000000;
overflow: hidden;
font-family: arial;
font-weight: normal;
filter:alpha(opacity=80);
-moz-opacity:0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
z-index: 3;
font-size: 10px;
line-height: 0.9em;
padding-top: 2px;
padding-right: 2px;
padding-bottom: 1px;
padding-left: 2px;
}

javascript代码:

function fixImage(image) {
// I want an to display an image of 200x331px taken from a directory of image of various dimensions
var show = document.getElementById("showImage");
if (image.height > image.width) {
    show.style.height = "331px";
    show.style.width = Math.round((image.width / image.height) * 331) + "px";
} else {
    show.style.width = "200px";
    show.style.height = Math.round((image.height / image.width) * 200) + "px";
}

show.src = image.src;
show.style.visibility = "visible";
}

var MAXPICTURENUMBER = 166; // or whatever you choose
var rn = 1 + Math.floor(MAXPICTURENUMBER * Math.random());
// Here I point to the directory containing the images and the caption
var url = "http://www.test.fr/Images/RandomPictures/" + rn + ".jpg";
var caption = "http://www.test.fr/Images/RandomPictures/" + rn + ".txt";

var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", caption, false);
xmlhttp.send();
captionText = xmlhttp.responseText;

window.onload = function () {
document.getElementById("theCaption").innerHTML = captionText;
document.getElementById("fullSize").src = url;
}

我确信有一个比我使用的更清洁/更智能的解决方案,但请记住,我是新手。

我的问题:这几乎正常工作,但文字有时会根据鼠标位置消失。我该如何解决这个问题?

Thkx提前为您提供帮助!!

1 个答案:

答案 0 :(得分:1)

我会将图片和标题放在同一个容器中。像

这样的东西
<div class="container">
    <img class="image" src="image.png" />
    <div class="caption">The caption</div>
</div>

和css

.caption{position:relative; top:-20px; height:20px; display:none;}
.container:hover .caption{display:block;}
然而,你可以显然风格。

编辑:这是最后的小提琴:http://jsfiddle.net/ES22a/5问题的一部分是jQuery冲突,所以头部还有一个jQuery.noConflict();