how to trigger(simulate) keyboard clicks programatically

时间:2018-02-03 09:48:43

标签: javascript javascript-events ecmascript-6

I am writing a function which when called will trigger the ctrl + , ctrl -, ctrl 0 key presses programatically. Which is to zoom in, zoom out or reset the page.

function zoom(type) {
  if (type === 'zoomIn') {
    // trigger the key combination ctrl and +
  } else if (type === 'zoomOut') {
    // trigger the key combination ctrl and -
  } else {
    // else restore to default - ctrl 0
  }
}

I hope it is allowed to do this and not restricted because of security issues. If not , then some ideas would be helpful.

1 个答案:

答案 0 :(得分:0)

You can achieve the save using following method, i.e. css zoom.

var zoom_level = 100;
function zoom(type) {
  if (type === 'zoomIn') {
    zoom_level += 100;
  } else if (type === 'zoomOut') {
    zoom_level -= 100;
  } else {
    zoom_level = 100;
  }
  document.body.style.zoom = zoom_level + '%';
}