如何通过PhantomJS触发MouseDown?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过PhantomJS触发MouseDown?相关的知识,希望对你有一定的参考价值。

我试过了:

var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent("mousedown", true, true);
jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0].dispatchEvent(clickEvent);

但它无法触发网站上的操作。没有错误返回。

答案

这是您以编程方式触发带有“mousedown”事件的DOM元素的单击的方式。要回答您的问题,您需要在源代码中包含两件事:

事件侦听器检测点击次数

jQuery行中多个选择器之间的逗号。

请运行下面的代码段,其中显示了修改后的jQuery行和正确运行的侦听器。

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      // You must have event listeners to see if anything is actually happening. For example, here I will add only a listener to the first element:
      jQuery(".left-rail-facets")[0].addEventListener('mousedown', function(e) {
        jQuery(".left-rail-facets")[0].innerHTML = "I have received a click.";
      }, false);
      // Now here is the code from your question. Please see how I have commas instead of spaces in my jQuery selector:
      var clickEvent = document.createEvent('MouseEvents');
     clickEvent.initEvent('mousedown', true, true);
      jQuery('.left-rail-facets,.facet-list,.facet.CS,.suggestion[data-value="B"],a')[0].dispatchEvent(clickEvent);
    });
  </script>
</head>

<body>

  <h1>I am a Webpage</h1>

  <p class="left-rail-facets">I have not received a click.</p>
  <p class="facet-list">I have not received a click.</p>
  <facet class="CS">I have not received a click.</facet>
  <p class="suggestion" data-value="B">I have not received a click.</p>
  <a href="url">I have not received a click.</a>

</body>

</html>
另一答案

您将需要使用document.createEvent和event.initMouseEvent:

var element = document.querySelector('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a');
//or var element = jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0];
var elementRect = element.getBoundingClientRect();
var mouseEvent = document.createEvent('MouseEvents');
mouseEvent.initMouseEvent('mousedown', true, true, window, 0, elementRect.left, elementRect.top);

以上是关于如何通过PhantomJS触发MouseDown?的主要内容,如果未能解决你的问题,请参考以下文章

JQuery如何实现双击事件时不触发单击事件

如何在 mousedown 元素之外捕获 mouseup 事件? (即正确的拖放?)

在触摸设备上触发 mousedown 和 mouseup

使用 jQuery 在初始 .mousedown() 事件后防止后续触发

为啥 IsMouseOver 被识别而 MouseDown 不是(Wpf 样式触发器)?

解决如何在点击按钮时,不触发input的失去焦点事件