简体   繁体   English

JS。 将事件属性类型分配给变量

[英]JS. assign event property type to a variable

Not sure how to formulate a question, need to assign something like a type of event to a variable and then use it. 不确定如何提出问题,需要将类似事件类型的内容分配给变量,然后使用它。 For instance: 例如:

mx = ('ontouchstart' in document.documentElement) ? event.changedTouches[0].pageX : event.pageX;

then: 然后:

function fn(e) {
  return mx - elem1.getBoundingClientRect().left;
}

that is e -event object goes to mx and returns the assigned earlier event type (so that мх is either e.changedTouches[0].pageX or e.pageX ). e -event对象转到mx并返回分配的较早事件类型(因此мхe.changedTouches[0].pageXe.pageX )。

Is it possible to do that? 有可能这样做吗? (otherwise, have to check for the support of ontouchstart each px of mouse move...) (否则,必须检查ontouchstart是否支持鼠标移动的每个像素...)

If you do not want to do the if check on every iteration, than just defined the function with the version you want. 如果您不想在每个迭代中都进行if检查,则可以使用所需的版本来定义函数。

var fn = (function () {
  if ('ontouchstart' in document.documentElement){
     return function(event){
         return event.changedTouches[0].pageX - elem1.getBoundingClientRect().left
     }
  } else {
     return function(event){
         return event.pageX - elem1.getBoundingClientRect().left
     }
  }
}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM