下面的代码使用本机addEventListener on mousedown,并结合shift单击。在这个函数中,我有一个名为lightweight-charts的本地函数subscribeCrosshairMove(),它允许我在横线移动时获取图表上的x值。
document.addEventListener('mousedown', function(e){
if(e.shiftKey == 1){
console.log('mouse and shift was pressed');
async function crossHairEvent(param){
try{
console.log(param.time);
}
catch{}
};
chart.subscribeCrosshairMove(crossHairEvent);
}
})我试图像下面这样赋值一个未定义的变量initialX,以分配来自十字的第一个X值:
let initialX;
if(initialX == undefined){
initialX = param.time;
console.log(initialX);
}
else{console.log('else')}将这段代码添加到try块中,我期望将十字头发中的第一个X值分配给initialX变量,因为在第一个赋值之后,它不再是undefined。但这不起作用。else语句从未被执行过。
当我移动游标时,console.log(initialX);一直在更改值。
我想从十字运动中回调第一个和最后一个值。我该怎么做?
edit1:所以我想出了如何从十字线上得到X的最后一个记录值。我只需将数据推入数组中,并取消对交叉移动的订阅。然后函数完成,我从数组中获取最后一个元素。
但是从数据中获取第一批数据给了我undefined,因为subscribeCrosshairMove()还没有正式结束,而十字线还在移动。在这里寻找建议或提示。谢谢..
发布于 2022-08-03 08:17:47
let initialX放置在块中。这意味着每次鼠标移动时,let initialX都会变得没有定义。param.time的值放在eventListener函数之外的某个地方。据我所知,您需要注册两个不同的值fromX和toX,这意味着您需要知道两个X坐标之间的距离。。
let coordinates = {
shiftKey: false,
fromX: null,
toX : null
}
let fromX = null;
let toX = null;
// Register the shiftKey pressing & releasing.
document.addEventListener('mousemove', function( e ){
if( e.shiftKey && !coordinates.shiftKey ) {
coordinates.shiftKey = true;
}
if( !e.shiftKey && coordinates.shiftKey ) {
coordinates.shiftKey = false;
}
})
async function crossHairEvent(param){
try{
// Register the fromX
if( coordinates.shiftKey && !coordinates.fromX ) {
coordinates.fromX = param.time;
}
// Register the toX
if( !coordinates.shiftKey && !coordinates.toX ) {
coordinates.fromX = param.time;
}
// Save the values in a deifferent variables.
if( coordinates.fromX && coordinates.toX ) {
fromX = coordinates.fromX;
toX = coordinates.toX ;
// Set them to null to make it possible to register every time you release the shiftKey.
coordinates.fromX = null;
coordinates.toX = null;
}
}
catch{}
};
chart.subscribeCrosshairMove(crossHairEvent);
这似乎是一个较长的解决方案,但它只是演示从eventListener中保存值的方法的一个示例。
https://stackoverflow.com/questions/73216698
复制相似问题