0

This is the situation:

I have a blog with several posts. Each post has images inside of it. With jQuery I am alreay wrapping the first image of each post so I can give it a unique styling.

Next to the styling I would also like to grab the first image of a post and use it as the header. The header already has a background so it should be replaced by, indeed, the first image of a post.

if ($("body").is("#permalink") && $(".imgwrapper").length>0) {
var firstImage = $(".imgwrapper").attr('src')
  $('#header-bg').css('background-image', "url(" + firstImage + ")")

}

Somehow the above code is not working and is giving me the following error in the console: resource interpreted as image but transferred with mime type text/html

Your help is much appreciated!

4

5 回答 5

2

像这样的工作:

http://jsfiddle.net/9Zk8G/

HTML

<div class="imgwrapper">
<img src="" />
</div>

JS

var firstImage="http://cdn-careers.sstatic.net/careers/gethired/img/3478c54721cd466fb6f7d3afe16e97d4.gif";  
$( "<img/>" ).attr( "src", firstImage ).appendTo( ".imgwrapper" );
于 2013-06-24T08:55:14.910 回答
1

你能检查firstImage. 如果 URL 按您的预期返回。代码没有错。

“资源解释为图像,但使用 mime 类型 text/html 传输”

Content-Type(响应标头)设置为text/html图像 URL ( firstName)。但是,当我们在背景图像中包含该 url 时,浏览器期望该 URL 返回图像(内容类型:image/*)。

浏览器会自动解释并显示为图像。如果图像损坏,请在新选项卡中打开图像 url 并检查内容。它可能会返回一些 HTML 内容本身。

于 2013-06-24T08:56:41.923 回答
0

您不需要属性url()中的部分css。尝试这个:

if ($("body").is("#permalink") && $(".imgwrapper").length > 0) {
    $('#header-bg').css('background-image', $(".imgwrapper").attr('src'))
}
于 2013-06-24T08:49:05.610 回答
0

解决了,仍然感谢所有的帮助和思考!这有效:

if ($("body").is("#permalink") && $(".imgwrapper").length>0) {
  var firstImage = $(".imgwrapper img").attr('src')
  $('#header-bg').css('background-image', "url(" + firstImage + ")")

}

我在这里犯的错误是我没有针对图像,而只是针对包装器。

于 2013-06-24T08:58:53.877 回答
0
if ($("body").is("#permalink") && $(".imgwrapper").length>0) {
var firstImage = $(".imgwrapper").attr('src');
$('#header-bg').css('background-image', "url(" + firstImage + ")");

}

那是因为你缺少“;”

于 2013-06-24T08:46:00.380 回答