有時候我們需要改變web風格,可是我們只會寫mobile,該怎麼辦呢?那就在網頁加入<style>標籤,設定CSS來達到我們的目的。
比如我們想在標頭H1呈現白字紅底,而現在是黑字白底。
就這麼做,WebView把網頁抓回來,網頁html中塞入<style>標籤,描述我們想要的效果。
/** Theme: WebView use CSS IDE: Xcode 6 Language: Objective C Date: 104/07/03 Author: HappyMan Blog: https://cg2010studio.wordpress.com/ */ NSString *urlString = [[NSString alloc] initWithFormat:@"http://..."]; url = [NSURL URLWithString:urlString]; NSData *data = [NSData dataWithContentsOfURL:url]; NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // 取代\n為<br/> string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>”]; // 標頭H1風格設為紅底白字 string=[@"<style>H1 {display: block;margin:5px;bgcolor:#ff0000;padding: 2px;color: white;border-bottom: 1px solid silver;background-color: #990000;}</style>" stringByAppendingString:string]; data = [string dataUsingEncoding:NSUTF8StringEncoding]; [displayWebView loadData:data MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
太棒了,由mobile端改變web端!
現在有很多網頁可測試CSS效果,比如這段html:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
background-color: #FF0000;
}
p {
background-color: #00FF00;
}
div {
background-color: #0000FF;
}
</style>
</head>
<body>
<h1>CSS background-color example!</h1>
<div>
This is a text inside a div element.
<p>This paragraph has its own background color.</p>
We are still in the div element.
</div>
</body>
</html>
這些程式碼在網頁上呈現的樣子如下:
隨意留個言吧:)~