使用JavaScript给UIWebView中的内容注入CSS

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"articleInline_small" ofType:@"css"];

    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    NSString *cssString = [[[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSString* css = [NSString stringWithFormat:@"\"%@\"", cssString];
    NSString* js = [NSString stringWithFormat:
                    @"var styleNode = document.createElement('style');\n"
                    "styleNode.type = \"text/css\";\n"
                    "var styleText = document.createTextNode(%@);\n"
                    "styleNode.appendChild(styleText);\n"
                    "document.getElementsByTagName('head')[0].appendChild(styleNode);\n", css];
    [webView stringByEvaluatingJavaScriptFromString:js];
    

 

 

 

参考:http://stackoverflow.com/questions/6903292/uiwebview-css-injection-using-javascript

你可能感兴趣的:(JavaScript)