我正在尝试开发一种能够通过使用上传的字体文件(TTF)动态更改元素字体的代码。下面的代码在Chrome,Opera和Firefox中运行良好,但在IE,Edge和Safari中无效。
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(name){
// set the font face
var f = new FontFace("myfont", "url(fonts/"+name+")", {});
f.load().then(function (loadedFace) {
document.fonts.add(loadedFace);
var fptags = document.getElementById('my-font');
fptags.style.fontFamily = "myfont, sans-serif";
});
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
这是php代码:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
echo $name;
?>
有人可以帮助我吗?我需要一个适用于每个流行浏览器的代码。感谢。
答案 0 :(得分:1)
IE和Edge不支持JavaScript void __fastcall TForm1::EmbeddedWBBeforeNavigate2(TObject *ASender, const IDispatch *pDisp,
OleVariant &URL, OleVariant &Flags, OleVariant &TargetFrameName, OleVariant &PostData,
OleVariant &Headers, WordBool &Cancel)
{
_di_IWebBrowser thisBrowser = pDisp;
_di_IWebBrowser parent = thisBrowser->Parent;
bool isFrame = ((!parent) || (parent == thisBrowser));
...
}
对象。您可能会更好地动态创建CSS FontFace
代码,如下所示:
@font-face
答案 1 :(得分:0)
按F12键尝试使用浏览器调试器并检查&lt; p&gt;上的字体。标签
<p id="my-font">
将其修复到控制台窗口并相应地更新代码。
答案 2 :(得分:0)
我找到了一个适用于Safari和Edge的解决方案,但它还不适用于IE。
非常难看,但有效:
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var font;
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(data){
$('link[rel=stylesheet][href="'+font+'.css"]').remove();
font = data;
$('head').append('<link rel="stylesheet" type="text/css" href="'+data+'.css">');
$('#my-font').css('font-family', 'myfont, sans-serif');
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
PHP脚本:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
$css = file_get_contents('font-face-aux.css');
$css = str_replace('?FONT_NAME?', $name, $css);
$f = fopen($name.'.css', 'w');
fwrite($f, $css);
fclose($f);
echo $name;
?>
辅助CSS:
@font-face {
font-family: 'myfont';
src: url('fonts/?FONT_NAME?');
}