web-模拟鼠标事件

鼠标事件:


function mouseEvent(type, sx, sy, cx, cy) {
  var evt;
  var e = {
    bubbles: true,
    cancelable: (type != "mousemove"),
    view: window,
    detail: 0,
    screenX: sx, 
    screenY: sy,
    clientX: cx, 
    clientY: cy,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    button: 0,
    relatedTarget: undefined
  };
  if (typeof( document.createEvent ) == "function") {
    evt = document.createEvent("MouseEvents");
    evt.initMouseEvent(type, 
      e.bubbles, e.cancelable, e.view, e.detail,
      e.screenX, e.screenY, e.clientX, e.clientY,
      e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
      e.button, document.body.parentNode);
  } else if (document.createEventObject) {
    evt = document.createEventObject();
    for (prop in e) {
    evt[prop] = e[prop];
  }
    evt.button = { 0:1, 1:4, 2:2 }[evt.button] || evt.button;
  }
  return evt;
}

function dispatchEvent (el, evt) {
  if (el.dispatchEvent) {
    el.dispatchEvent(evt);
  } else if (el.fireEvent) {
    el.fireEvent('on' + type, evt);
  }
  return evt;
}


用例:


var canvas = document.getElementsByTagName("canvas")[0];
  	var pageX = canvas.offsetLeft + (315 / 414) * canvas.offsetWidth;
  	var pageY = canvas.offsetTop + (30 / 600) * canvas.offsetHeight;

  	var event = mouseEvent("mousedown", pageX, pageY, pageX, pageY);
  	dispatchEvent(canvas, event);

  	var event = mouseEvent("mouseup", pageX, pageY, pageX, pageY);
  	dispatchEvent(canvas, event);


jquery版本:

var $canvas = $("#c2canvas");
	var offset = $canvas.offset();
	var restartPageX = offset.left + 0.5 * $canvas.width();
	var restartPageY = offset.top + (408 / 435) * $canvas.height();

	var e1 = new jQuery.Event("mousedown");
	e1.pageX = restartPageX;
	e1.pageY = restartPageY;
	var e2 = new jQuery.Event("mouseup");
	e2.pageX = restartPageX;
	e2.pageY = restartPageY;
	$(document).trigger(e1).trigger(e2);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值