使用javascript设置背景图像 [英] Setting background-image with javascript
问题描述
在chrome,safari和opera中,将背景图片设置为绝对引用,例如:/images/image.png将其更改为 http://sitepath/images/image.png 。
In chrome, safari, and opera setting the background image to an absolute reference such as: "/images/image.png" changes it to "http://sitepath/images/image.png".
它不会在firefox中执行此操作。
It does not do this in firefox.
有没有办法避免这种行为,还是写入浏览器的javascript引擎?使用jquery设置background-image也会出现这个问题。
Is there any way to avoid this behavior, or is it written into the browser's javascript engine? Using jquery to set the background-image also does this problem.
问题是,我将HTML发布到需要特定格式的URL的PHP脚本。我知道设置图像路径相对修复了这一点,但我不能这样做。
The problem is that I am posting the HTML to a php script that needs the urls in this specific format. I know that setting the image path relative fixes this, but I can't do that.
唯一的另一个选择是使用regexp。
The only other alternative would be to use a regexp. to convert the urls.
在firefox和chrome / webkit浏览器中测试:
Thanks.
Test this in firefox, and chrome / webkit browser:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div style="height:400px;width:400px;background-image:url(/images/images/logo.gif);">
</div>
<br />
<br />
<div id="test" style="height:400px;width:400px;">
</div>
<script type="text/javascript" src="/javascripts/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#test").css('background-image',"url(/images/images/logo.gif)");
alert(document.getElementById('test').style.backgroundImage);
});
</script>
</body>
</html>
推荐答案
不确定如何将该位置该文档,但您可以使用 window.location.hostname
获取该域并添加该域。
Not sure exacly how you're putting that location into the document, but you can use window.location.hostname
to get the domain and prepend that.
var bgImg = window.location.hostname + '/images/images/logo.gif';
$("#test").css('background-image', 'url('+bgImg+')');
您将替换 /images/images/logo.gif
但是你生成的图像(服务器端,我猜?)
You would replace /images/images/logo.gif
with however you generate the image (server-side, I guess?)
这篇关于使用javascript设置背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!