将鼠标悬停在CasperJS上

时间:2015-04-24 11:06:13

标签: javascript hover casperjs

如何在悬停在元素上后变为可见的元素上执行click事件。 下面是HTML代码

<div class="jqtree-element jqtree_common">
<span class="jqtree-title jqtree_common" contenteditable="true">Notebook 1</span>
<span class="notebook-right">
<span class="notebook-date disappear" style="visibility: visible;">
<span class="notebook-commands-right">
<span class="notebook-commands appear-wrapper">
<span class="notebook-commands appear" style="display: none;">
<span class="fontawesome-button info">
<span class="fontawesome-button history">
<span class="fontawesome-button private">
<span class="fontawesome-button public" style="display: none;">
<span class="fontawesome-button remove">
<i class="icon-remove"></i>
</span>
</span>
</span>
</span>
</div>

删除笔记本我正在使用以下代码

casper.then(function(){
  if(this.visible({type:'xpath', path:'/html/body/div[3]/div/div[1]/div[1]/div/div/div[1]/div[2]/div/div/ul/li[1]/ul/li[1]/ul/li[11]/div/span[2]/span[3]/span/span[5]/i'}))
  {
    this.click({type:'xpath', path:'/html/body/div[3]/div/div[1]/div[1]/div/div/div[1]/div[2]/div/div/ul/li[1]/ul/li[1]/ul/li[11]/div/span[2]/span[3]/span/span[5]/i'});
    });
    console.log('notebook '+ title +' deleted');
  } else {
     console.log('element not found');
  }
});

在控制台中显示“无法调度mousedown事件..”

2 个答案:

答案 0 :(得分:5)

CasperJS具有具有move()功能的鼠标模块。它需要一个坐标或一个选择器。 CasperJS将使用底层的PhantomJS sendEvent()函数来创建本机事件。

casper.mouse.move(someCSSSelector);

var x = require('casper').selectXPath;
...
casper.mouse.move(x(someXPathExpression));

如果页面在此之后加载了某些内容,可能需要在移动鼠标后稍等一下:

casper.mouse.move(someCSSSelector);
casper.waitUntilVisible(expectedElementSelector, function(){
    this.click(expectedElementSelector);
});

几乎所有函数都可以使用XPath表达式和CSS选择器。

答案 1 :(得分:1)

如果我没错,我猜你的意思是触发点击事件。 它可以用原生的javascript完成,就是这样:

var note = document.getElementById('note');
note.onclick = function(){
  alert('Someone click me');
}

var evtClick = document.createEvent('Event');
evtClick.initEvent('click', true, true);
note.onmouseover = function() {
  this.dispatchEvent(evtClick);
};
<b id='note'>Hover me!</b> It will trigger click event.