草庐IT

JavaFx WebView - 滚动到所需位置

coder 2024-03-20 原文

我正在尝试创建一个 WebView 并向其中添加内容。单击按钮将内容附加到 Web View 。在这里,我需要以编程方式将 Web View 滚动到所需的位置,比如 (0, 60)。我尝试使用 JavaScript 并使用 ScrollBar 类的 setValue。但没有任何效果。这是示例,

public class FxWebViewSample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        Group root = new Group();

        final WebView wView = new WebView();
        wView.setId("my_view");
        wView.setPrefHeight(200);
        wView.setPrefWidth(200);
        final WebEngine engine = wView.getEngine();
        engine.loadContent("<body contentEditable='true'><div id='content'>Initial Text</div><div id='first'>My first web view in fx</div></body><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><div id='first'>My first web view in fx</div></body></body>");

        Button appendbtn = new Button("Append Text to Web View");

        TextArea area = new TextArea();
        area.setText("My text area");

        VBox vBox = new VBox();
        vBox.getChildren().addAll(wView, appendbtn);
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 300);
        primaryStage.setScene(scene);
        primaryStage.show();

        appendbtn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent arg0) {
                /** To append html and text contents to web view */
                String webViewContents = (String) engine
                        .executeScript("document.documentElement.outerHTML");
                String appendContent = "<div>Appended html content</div> Appended text content";
                engine.loadContent(webViewContents + appendContent);

                /**JavaScript to scroll the view*/
                //String scrollJsFtn = "var elem = document.getElementById('my_view');var x = 0;var y = 0;while (elem != null) {x += elem.offsetLeft;y += elem.offsetTop;elem = elem.offsetParent;}window.scrollTo(30, 30);";
                //engine.executeScript(scrollJsFtn);

                Set<Node> scrollBars = wView.lookupAll(".scroll-bar");
                for (Node node : scrollBars) {
                    if (node instanceof ScrollBar) {
                        ScrollBar sBar = (ScrollBar) node;
                        sBar.setValue(100.0);
                    }
                }
            }
        });

    }
}

有没有办法以编程方式设置网页 View 的滚动条位置?

最佳答案

想办法。使用 JavaScript,可以以编程方式滚动 Web View 。

public class FxWebViewSample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        Group root = new Group();

        final WebView wView = new WebView();
        wView.setId("my_view");
        wView.setPrefHeight(200);
        wView.setPrefWidth(200);
        final WebEngine engine = wView.getEngine();
        engine.setJavaScriptEnabled(true);
        engine.loadContent("<body contentEditable='true'><div id='content'>Initial Text</div><div id='first'>My first web view in fx</div></body><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><span id='second'>My first web view in fx</span><div id='first'>My first web view in fx</div></body></body>");

        Button appendbtn = new Button("Append Text to Web View");

        TextArea area = new TextArea();
        area.setText("My text area");

        VBox vBox = new VBox();
        vBox.getChildren().addAll(wView, appendbtn);
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 300);
        primaryStage.setScene(scene);
        primaryStage.show();

        appendbtn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent arg0) {
                /** To append html and text contents to web view */
                String webViewContents = (String) engine
                        .executeScript("document.documentElement.outerHTML");
                String appendContent = "<div id='append'>Appended html content</div> Appended text content";

                StringBuilder scrollHtml = scrollWebView(0, 50);

                engine.loadContent(scrollHtml + webViewContents + appendContent);
            }
        });

    }

    public static StringBuilder scrollWebView(int xPos, int yPos) {
        StringBuilder script = new StringBuilder().append("<html>");
        script.append("<head>");
        script.append("   <script language=\"javascript\" type=\"text/javascript\">");
        script.append("       function toBottom(){");
        script.append("           window.scrollTo(" + xPos + ", " + yPos + ");");
        script.append("       }");
        script.append("   </script>");
        script.append("</head>");
        script.append("<body onload='toBottom()'>");
        return script;
    }
}

关于JavaFx WebView - 滚动到所需位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22778241/

有关JavaFx WebView - 滚动到所需位置的更多相关文章

  1. ruby - 正则表达式在哪个位置失败? - 2

    我需要一个非常简单的字符串验证器来显示第一个符号与所需格式不对应的位置。我想使用正则表达式,但在这种情况下,我必须找到与表达式相对应的字符串停止的位置,但我找不到可以做到这一点的方法。(这一定是一种相当简单的方法……也许没有?)例如,如果我有正则表达式:/^Q+E+R+$/带字符串:"QQQQEEE2ER"期望的结果应该是7 最佳答案 一个想法:你可以做的是标记你的模式并用可选的嵌套捕获组编写它:^(Q+(E+(R+($)?)?)?)?然后你只需要计算你获得的捕获组的数量就可以知道正则表达式引擎在模式中停止的位置,你可以确定匹配结束

  2. 即使安装了 gem,Ruby 也找不到所需的库 - 2

    我花了几天时间尝试安装ruby​​1.9.2并让它与gems一起工作:-/我最终放弃了我的MacOSX10.6机器,下面是我的Ubuntu机器上的当前状态。任何建议将不胜感激!#rubytest.rb:29:in`require':nosuchfiletoload--mongo(LoadError)from:29:in`require'fromtest.rb:1:in`'#cattest.rbrequire'mongo'db=Mongo::Connection.new.db("mydb")#gemwhichmongo/usr/local/rvm/gems/ruby-1.9.2-p0/g

  3. ruby - Rails -- :id attribute? 所需的数据库索引 - 2

    因此,当我遵循MichaelHartl的RubyonRails教程时,我注意到在用户表中,我们为:email属性添加了一个唯一索引,以提高find的效率方法,因此它不会逐行搜索。到目前为止,我们一直在根据情况使用find_by_email和find_by_id进行搜索。然而,我们从未为:id属性设置索引。:id是否自动索引,因为它在默认情况下是唯一的并且本质上是顺序的?或者情况并非如此,我应该为:id搜索添加索引吗? 最佳答案 大多数数据库(包括sqlite,这是RoR中的默认数据库)会自动索引主键,对于RailsMigration

  4. ruby - 下载位置 Selenium-webdriver Cucumber Chrome - 2

    我将Cucumber与Ruby结合使用。通过Selenium-Webdriver在Chrome中运行测试时,我想将下载位置更改为测试文件夹而不是用户下载文件夹。我当前的chrome驱动程序是这样设置的:Capybara.default_driver=:seleniumCapybara.register_driver:seleniumdo|app|Capybara::Selenium::Driver.new(app,:browser=>:chrome,desired_capabilities:{'chromeOptions'=>{'args'=>%w{window-size=1920,1

  5. ruby - Heroku production.log 文件位置 - 2

    我想在heroku.com上查看我的应用程序日志的内容,所以我关注了thisexcellentadvice并拥有我所有的日志内容。但是我现在很想知道我的日志文件实际在哪里,因为“log/production.log”似乎是空的:C:\>herokuconsoleRubyconsoleforajpbrevx.heroku.com>>files=Dir.glob("*")=>["public","tmp","spec","Rakefile","doc","config.ru","app","config","lib","README","Gemfile.lock","vendor","sc

  6. ruby - 在 Ruby 中查找多个正则表达式匹配的模式和位置 - 2

    这应该是一个简单的问题,但我找不到任何相关信息。给定一个Ruby中的正则表达式,对于每个匹配项,我需要检索匹配的模式$1、$2,但我还需要匹配位置。我知道=~运算符为我提供了第一个匹配项的位置,而string.scan(/regex/)为我提供了所有匹配模式。如果可能,我需要在同一步骤中获得两个结果。 最佳答案 MatchDatastring.scan(regex)do$1#Patternatfirstposition$2#Patternatsecondposition$~.offset(1)#Startingandendingpo

  7. ruby - TypeError(救援条款所需的类或模块) - 2

    我已经使用Stripe一年多了,基于RyanBates的RailsCast插曲发现here.但是,我的错误处理最近停止工作,而且我以前从未见过此错误。我最近开始在Ruby2.1上运行我的应用程序,据我所知,这就是问题所在。这是我的订阅模型中的一个实例方法:beginsave_with_stripe_paymentrescueStripe::InvalidRequestError=>elogger.error"Stripeerrorwhilecreatingcustomer:#{e.message}"logger.errore.backtrace.join("\n")errors.add

  8. ruby-on-rails - 尝试打开 .gitignore 以在文本编辑器中对其进行编辑,但在 OS X Mountain Lion 上找不到文件位置 - 2

    我使用“newapp_name”创建了一个新的Rails应用程序,我正在尝试编辑.gitignore文件,但在我的应用程序文件夹中找不到它。我在哪里可以找到它?我安装了Git。 最佳答案 .gitignore位于项目的root中,而不是app子目录中。首先打开终端并进入您的目录。您需要使用ls-a来显示stash文件。然后使用打开.gitignore 关于ruby-on-rails-尝试打开.gitignore以在文本编辑器中对其进行编辑,但在OSXMountainLion上找不到文件位

  9. ruby-on-rails - Ruby 如何知道在哪里可以找到所需的文件? - 2

    这里还有一个新手问题:require'tasks/rails'我在每个Rails项目的根路径中的Rakefile中看到了这一行。我猜这行用于要求vendor/rails/railties/lib/tasks/rails.rb加载所有rake任务:$VERBOSE=nil#LoadRailsrakefileextensionsDir["#{File.dirname(__FILE__)}/*.rake"].each{|ext|loadext}#LoadanycustomrakefileextensionsDir["#{RAILS_ROOT}/lib/tasks/**/*.rake"].so

  10. ruby-on-rails - 在 Rails 中存储(结构化)配置数据的位置 - 2

    对于我正在编写的Rails3应用程序,我正在考虑从本地文件系统上的XML、YAML或JSON文件中读取一些配置数据。重点是:我应该把这些文件放在哪里?Rails应用程序中是否有用于存储此类内容的默认位置?附带说明一下,我的应用程序部署在Heroku上。 最佳答案 我经常做的是:如果文件是通用配置文件:我在目录/config中创建一个YAML文件,每个环境有一个上层key如果我为每个环境(大项目)创建一个文件:我为每个环境创建一个YAML并将它们存储在/config/environments/然后我在加载YAML的地方创建了一个初始化

随机推荐