简体   繁体   中英

change webView font-family via javaScript in android

I am developing an Epub Reader application. I need to add changing font tool in my application. I have problem in my JavaScript side.

My app opens different Epub files and therefore I can not predict Epub HTML,CSS files content .

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.

changeFont 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). So you have to remove inline styles first:

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

or using pure 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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