我正在JavaFx中创建一个示例应用程序。 我在appview中加载了一个本地html文件。我想从应用程序将样式应用于加载的html页面。当我尝试这样做时,样式将应用于整个webview。 我只想申请加载的html页面,而不是webview。
这是我正在加载的index.html页面。
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()" id="btn">Try it</button>
</body>
</html>
这是demo.css
*{
padding: 0;
margin: 0;
}
#btn{
font-weight: bold;
font-size: 14px;
padding: 10px 20px;
}
body {
background-color: #00ff80;
font-family: Arial, Helvetica, san-serif;
}
这是我的javafx应用代码。
Hyperlink hpl3 = new Hyperlink("Load Html File");
hpl3.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
String path = System.getProperty("user.dir");
path.replace("\\\\", "/");
path += "/html/index.html";
String path1 = System.getProperty("user.dir");
path1.replace("\\\\", "/");
path1 += "/css/demo.css";
webEngine.setUserStyleSheetLocation("file:///" + path1);
webEngine.load("file:///" + path);
}
});
答案 0 :(得分:-1)
正如james-d所说:
import javafx.application.Application;
import javafx.concurrent.Worker.State;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class WebViewCssPlay extends Application {
private static final String CSS =
"body {"
+ " background-color: #00ff80; "
+ " font-family: Arial, Helvetica, san-serif;"
+ "}";
@Override
public void start(Stage stage) {
stage.setTitle("CSS Styling Test");
stage.setWidth(300);
stage.setHeight(200);
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
if (newState == State.SUCCEEDED) {
Document doc = webEngine.getDocument() ;
Element styleNode = doc.createElement("style");
Text styleContent = doc.createTextNode(CSS);
styleNode.appendChild(styleContent);
doc.getDocumentElement().getElementsByTagName("head").item(0).appendChild(styleNode);
System.out.println(webEngine.executeScript("document.documentElement.innerHTML"));
}
});
webEngine.loadContent("<html><body><h1>Hello!</h1>This is a <b>test</b></body></html>");
VBox root = new VBox();
root.getChildren().addAll(browser);
root.getStyleClass().add("browser");
Scene scene = new Scene(root);
stage.setScene(scene);
//scene.getStylesheets().add("/net/snortum/play/web_view.css");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
<强>来源:强>