Вопрос

I use an editable QWebView and write some text on it. I want to get current element that text cursor point to it and do some changes. For example text cursor is in a <p> tag that haven't any Id or class. I want to get this paragraph and set it's display to none for example.

How can I get the current element that haven't any Id or class?

I tried: this.style.display="none" it didn't work, but when I try document.getElementsByTagName('p')[0].style.display="none" it works. And I don't know how can i get the current element.

Point that I want to do this just with javascript, not jquery. and without any click or etc. Is it possible? How can i do this?

How does execCommand work? for example how execCommand justifyRight get the current element?

This is my code:

QWebFrame *frame = p->webView->page()->mainFrame();
QString js = QString("this.style.display='none'");
frame->evaluateJavaScript(js);

Thank you

Это было полезно?

Решение

In the case of an editable web page, ideally we'd want to be able to ask the QWebFrame in what QWebElement is the caret, at any time. Then we could tweak this element with C++ code.

Unfortunately, according to the documentation, no such method is provided.

Anyway, there's a workaround in webkit's javascript since we can access the user selection or the caret's position in the DOM with window.getSelection(). Here's some code that finds the nearest <p> tag above the selection and changes its style as needed:

  QString js=
  "  var node = window.getSelection().getRangeAt(0).startContainer;"
  "  while (node) {"
  "    if (node.nodeName.toUpperCase()=='P') {"
  "      node.style.display='none';"
  "      break;"
  "    }"
  "    node=node.parentNode;" 
  "  }" ;

  QVariant res = page()->mainFrame()->evaluateJavaScript(js);

You might want to generalize it to take node types and styles as parameters, and possibly test it a bit (I'm no JS expert), but the I believe the principle is sound.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top