2012-06-11 52 views

回答

4
<h1><img src="heading.png" alt="Some nice heading here" 
     width="600" height="80"></h1> 

使用alt属性和设置图像尺寸(HTML或CSS),以确保浏览器可以获取图像之前分配适当的空间。您还可以将CSS样式应用于img元素,例如,字体,大小和颜色;在现代浏览器中,当图像还没有得到(或曾经)时,样式将被应用于替代文本。使用上面的代码,您可以在h1元素上设置样式。

Altenatively,只使用(样式)文本最初的标题,但使用图像替换它的JavaScript:

<h1 style="width: 600px; height: 80px">Some nice heading here</h1> 
<script> 
new Image('heading.png'); // preloads the image 
var h1 = document.getElementsByTagName('h1')[0]; 
h1.innerHTML = '<img src=heading.png alt="' + h1.innerHTML + '">'; 
</script> 
+0

你如何确定图像尺寸? (要指出的是,经常有*不是这样做的一种方式。) – Michael

1

使用Alt标签,但即使这样也不能保证:

<img src="yourimagepath" alt="Title Text" title="Title Text" /> 

或者,你可以破解使用JS:设置你的网页文本的标题和图像替换标题容器的内容在完整页面加载后使用JS。

1

您可以动态加载jQuery中的图片,只需要很少量的代码。如果你喜欢这种方式,你可以做一些流畅的事情,比如放置“加载...”动画或AJAX旋转器代替你的内容。

从jQuery的文档

var _url = "image.jpg"; 

// set up the node/element 
_im =$("<img>"); 

// hide and bind to the load event 
_im.hide(); 
_im.bind("load",function(){ $(this).fadeIn(); }); 

// append to target node/element 
$('body div#target').append(_im); 

// set the src attribute now, after insertion to the DOM 
_im.attr('src',_url); 
在伪

上的注释,并创建一个隐藏图像元素,分配一个onload事件处理程序,设置src属性动态加载图像。处理程序顺利淡化图像。

+0

他的问题没有标签'jQuery' – Sarfraz

+3

我不认为这是有道理的使用jQuery的只有这一点(除非OP已经使用jQuery。这是一个矫枉过正的imo –

+0

是的,我想提供一个“流畅”的解决方案,而不是依赖alt文本,这不是一个很好的用户体验。 –

3

如何这 -

<div id="img">some text</div> 
<script> 
$(document).ready(function(){ 
    $("#img").innerHTML="<img src="myimg.jpg">" 
    }); 
}); 
</script> 

jQuery是一个不错的选择做这:-)