簡體   English   中英

在 webview 中滾動到具有給定名稱屬性的 HTML 元素

[英]Scroll to HTML element with given name attribute in webview

我在 swift 中使用UIWebView ,它使用webView.loadHTMLString從數據庫字符串加載 HTML

這是我正在加載的 HTML 示例:

</p>\r\n<p>
<a name="bm001">**</a>
Physicists think the invisible dark matter must exist because they can see its\r\ngravitational effects on visible matter throughout the cosmos. But no one knows \r\nwhat it's actually made of. Among the leading candidates are weakly interacting \r\nmassive particles, or WIMPs, but scientists have <span style="color:red;">hunted for them for decades with \r\nno success</span>


</p>\r\n<p><a name="bm002"></a>
Theoretically, macros could have almost any size and mass. And because dark matter \r\ndoesn't interact with regular matter, there would be nothing to stop these particles \r\nfrom zipping around unimpeded. So Starkman - along with Case Western physicist Jagjit \r\nSingh Sidhu and physicist Robert Scherrer of Vanderbilt University in Nashville \r\n- decided to do a gut check using human flesh as a dark matter detector.</p>\r\n<p>If a macro as small as a square micrometer zipped through your body at hypersonic \r\nspeed, it would deposit about as much energy in your body as a typical metal bullet, \r\nthe team calculated. But the damage it caused would be different from that of a \r\nbullet: A macro would heat the cylinder of tissue in its wake to about  10,000,000&#176; \r\nCelsius - vaporizing the tissue and leaving a path of plasma.</p>

<p><a name="bm003"></a>Next, Starkman and Sidhu plan to look for macro tracks in slabs of granite, which \r\nwould appear as cylinders of black obsidian running straight through the rock. They're \r\nstarting with a cemetery near the Case Western campus.</p>

現在我想要實現的功能是通過按下按鈕滾動到名稱標簽。 例如。 在以下 HTML 內容中,有三個<a>標簽包含不同的名稱,即name="bm001",name="bm002",name="bm003"

現在,如果我按下按鈕 1,它將滾動到包含 bm001 的段落,如果我按下按鈕 2,它將滾動到包含 bm002 的段落,其他標簽也類似。

有什么辦法可以實現這個功能嗎?

您可以將 JavaScript 注入您的 webview 以執行滾動操作,如下所示:

// Call this once when the page loads:

func setupPageScrolling() -> Bool {
  let functionJSCode = """
  function scrollToElement(name) {
     const element = document.querySelector("[name='" + name + "']");
     if (element == null) {
        console.log("cannot find element with name '" + name + "'");
        return false;
     }

     element.scrollIntoView({"behavior": "smooth"});
     return true;
  }

  typeof scrollToElement === "function"
  """

  return webView.stringByEvaluatingJavaScript(from: functionJSCode) == "true"
}

定義一個 Swift 函數以在您想要執行滾動操作時調用:

func scrollTo(name: String) -> Bool {
   return webView.stringByEvaluatingJavaScript(from: "scrollToElement('" + name + "')") == "true"
}

根據需要調用它。

參考:

UIWebView.stringByEvaluatingJavaScript(from:)

Document.querySelector()

Element.scrollIntoView()


完整的工作示例(使用 Xcode 11.3.1 測試):

import UIKit

let html = """
  <html>
    <head>
      <title>Testing</title>
    </head>
    <body>
      
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
        But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
        At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
      </p>
      
      <a name="foo">Link</a>

<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
  But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
  At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</p>
    </body>
</html>
"""

class ViewController: UIViewController {
    let webView = UIWebView()
        
    override func viewDidLoad() {
        super.viewDidLoad()
    
        webView.delegate = self
        webView.frame = self.view.bounds
        webView.loadHTMLString(html, baseURL: nil)
        self.view.addSubview(webView)
    }
}

extension ViewController : UIWebViewDelegate {
    func setupPageScrolling() -> Bool {
      let functionJSCode = """
      function scrollToElement(name) {
         var element = document.querySelector("[name='" + name + "']");
         if (element == null) {
            console.log("cannot find element with name '" + name + "'");
            return false;
         }

         element.scrollIntoView({"behavior": "smooth"});
         return true;
      }

      typeof scrollToElement === "function"
      """

      return webView.stringByEvaluatingJavaScript(from: functionJSCode) == "true"
    }
    
    func scrollTo(name: String) -> Bool {
       return webView.stringByEvaluatingJavaScript(from: "scrollToElement('" + name + "')") == "true"
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        guard setupPageScrolling() else {
            print("Couldn't setup page scrolling JS function!")
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
            guard self.scrollTo(name: "foo") else {
                print("Couldn't scroll to element with name \"foo\"")
                return
            }
        }
    }
}

演示視頻https : //share.getcloudapp.com/KouWqlkG

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM