[英]Problems with getting background-image using Javascript in IE and Chrome
我有一個允許用戶標記圖片的網站。 標簽可以投票。 我對標簽進行排序有兩個選項:“頂部排序”和“新排序”,這很容易解釋。 當用戶單擊例如“ sort new”時,此JS函數稱為:
<script type="text/javascript">
function sortTagsNew()
{
var sortnew = document.getElementById('sortnew');
var sorttop = document.getElementById('sorttop');
sortnew.style.textDecoration = 'underline';
sorttop.style.textDecoration = 'none';
var filename = document.getElementById('center_frame').style.backgroundImage;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("response_caption").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sortnew.php?filename="+filename,true);
xmlhttp.send();
}
</script>
您可能可以說大的IF語句進行了AJAX調用。 它引用了以下PHP文件sortnew.php
,該文件在數據庫中查詢該圖像下的標簽。
$capfilename = $_GET['filename'];
$acturl = substr($capfilename, 6, -3); //extracts filename from the url('')
$new_captions = mysql_query("SELECT * from captions where image = '$acturl' ORDER BY time DESC LIMIT 5");
$caption = array();
while($rows = mysql_fetch_array($new_captions)){
$caption[] = $rows;
// Includes a PHP file that designates how tags should be displayed (uses a foreach), but that's kind of irrelevant.
我認為問題是,IE和Chrome無法通過filename
訪問。 當我手動輸入帶有標簽的有效圖像的文件名時,它可以正常工作,但是無論出於何種原因,IE和Chrome都不會獲得文件名,因此不會返回任何內容。 我認為這可能與我如何使用子字符串提取文件名本身有關。 也許Chrome和IE會自動獲取文件名,但我找不到任何相關信息。 請記住,它確實在FF 中起作用。
在不同的瀏覽器中,不同的css url呈現方式存在一些問題:
在Chrome中:
> document.getElementById('center_frame').style.backgroundImage;
"url(http://3.bp.blogspot.com/-8R0NUSKVupc/TfI92fvQY1I/AAAAAAAAAeA/B6e09X9hhqY/s1600/4.jpg)"
> document.getElementById('center_frame').style.backgroundImage.length;
90
在Opera中:
>>> document.getElementById('center_frame').style.backgroundImage;
"url("http://3.bp.blogspot.com/-8R0NUSKVupc/TfI92fvQY1I/AAAAAAAAAeA/B6e09X9hhqY/s1600/4.jpg")"
>>> document.getElementById('center_frame').style.backgroundImage.length;
92
如您所見,這兩個字符串在Opera和Chrome中是不同的(我不知道其他瀏覽器)。 因此,首先您應該解析它並轉換為通用格式(http://example.com/test.jpg),然后再使用它。
解析backgroundImage字符串的代碼(僅在rhino中測試):
/// Simple parsing
function parse1(str) {
str = str.slice(4, -1);
if (str[0] == '"' || str[0] == "'") {
return str.slice(1, -1);
}
return str;
}
// Regular Expressions magic
function parse2(str) {
return str.match(/^url\(['"]?([^'"]+)['"]?\)$/)[1];
}
a = "url(\"http://3.bp.blogspot.com/-8R0NUSKVupc/TfI92fvQY1I/AAAAAAAAAeA/B6e09X9hhqY/s1600/4.jpg\")";
b = "url(http://3.bp.blogspot.com/-8R0NUSKVupc/TfI92fvQY1I/AAAAAAAAAeA/B6e09X9hhqY/s1600/4.jpg)";
print(parse1(a));
print(parse1(b));
print(parse2(a));
print(parse2(b));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.