我在JavaFx中創建一個示例應用程序。 我已經在web瀏覽器中加載了一個本地html文件。我想將樣式應用於從應用程序加載的HTML頁面。當我嘗試這樣做時,風格適用於整個webview。 我只想應用於加載的HTML頁面而不是webview。在javafx的webview中應用Css內容
這是我加載的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);
}
});
[應用CSS文件的JavaFX的WebView](可能的重複http://stackoverflow.com/問題/ 32783532/apply-css-file-to-javafx-webview) – DVarga
不要嘗試自己創建文件URL。 java庫中有類爲你做這些事情:'Path base = Paths.get(System.getProperty(「user.dir」)); String path = base.resolve(Paths.get(「html」,「index.html」))toUri()。toURL()。toExternalForm();' – fabian