简体   繁体   English

通过 android 中的 javaScript 更改 webView 字体系列

[英]change webView font-family via javaScript in android

I am developing an Epub Reader application.我正在开发一个Epub 阅读器应用程序。 I need to add changing font tool in my application.我需要在我的应用程序中添加更改字体工具。 I have problem in my JavaScript side.我的JavaScript方面有问题。

My app opens different Epub files and therefore I can not predict Epub HTML,CSS files content .我的应用程序打开不同的 Epub 文件,因此我无法预测Epub HTML,CSS 文件内容

My function works for elements that doesn't have font-family attribute and it doesn't effect on elements could have font-family attributes like p , body and h tags.我的 function 适用于没有font-family属性的元素,并且它不影响可能具有font-family属性的元素,例如pbodyh标签。

changeFont function:更改字体function

 function changeFont(fontIndex) { var fontFamilyValues = ["aldhabi.ttf", "b_nazanin.TTF", "b_nazanin_outline.ttf", "iransanse_mobile.ttf"]; var newStyle = document.createElement('style'); var font=fontFamilyValues[fontIndex]; var fontUrl="file:///android_asset/fonts/"+font; var fontName=font.substring(0,font.lastIndexOf('.')); newStyle.appendChild(document.createTextNode("@font-face{ font-family:"+fontName+";src: url("+fontUrl+");}")); document.head.appendChild(newStyle); newStyle.appendChild(document.createTextNode("*{font-family:"+fontName+";}")); }

inline style overrides <style> block (and style block overrides external css file).内联样式覆盖<style>块(并且样式块覆盖外部 css 文件)。 So you have to remove inline styles first:所以你必须首先删除内联 styles :

$("*").css('font-family', '');

or using pure javascript:或使用纯 javascript:

 var all = document.getElementsByTagName("*");
 for (var i=0; i < all.length; i++) 
 {    
     all[i].style.removeProperty('font-family');
 }

to force your new style over everything else you can also apply:important on your styles like this:强迫你的新风格超越你也可以应用的一切:在你的 styles 上很重要,如下所示:

newStyle.appendChild(document.createTextNode("*{font-family:"+fontName+" !important;}"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM