触发通话的Mousedown和Mouseup问题?

时间:2019-01-16 10:48:43

标签: javascript jquery

  

在我的代码中,我使用两个按钮来显示与   与两种颜色相同的页面。当我单击绿色3秒钟后   只有我发出呼叫并显示相关数据。红色按钮作为常规功能起作用。

我的问题是第一次单击TRY IT GREEN按钮3秒钟,它什么也没做,我必须第二次单击3秒钟才能显示绿色。单击“尝试绿色”按钮2次后,将来也只需单击一下即可使用。

  

任何帮助将不胜感激,这样我就不必单击两个   次开始。

[1, 3, 4, 2, 2, 5, 5, 5, 6, 6, 6, 6]
   
var pressme = document.getElementById('pressme');
var button1=document.getElementById('myBtn');
var button2=document.getElementById('myBtn1');

var showme = document.getElementById('showme');
button1.addEventListener('click', display1

);
button2.addEventListener('click', display2
 
);
function display1(){                              //displaying red background
    pressme.style.display = 'none';
    showme.style.display = 'block';
    button1.style.display=  'none';
    button2.style.display=  'block';



}

function display2(){          //displaying green background after 3 sec
    

let timeout = null;
     button2.addEventListener( 'mousedown', event => {
     timeout = setTimeout(() => {
     pressme.style.display = 'block';
     showme.style.display = 'none';
     button2.style.display=  'none';
     button1.style.display=  'block';

      }, 3000 );
     });
    button2.addEventListener( 'mouseup', event => {
                                    
    if ( timeout ) clearTimeout( timeout );
      });

}

1 个答案:

答案 0 :(得分:2)

您需要先附加eventListener,问题是单击按钮后已附加了鼠标事件侦听器,因此它们第一次无法使用。

工作代码:

var pressme = document.getElementById('pressme');
var button1=document.getElementById('myBtn');
var button2=document.getElementById('myBtn1');

var showme = document.getElementById('showme');

button1.addEventListener('click', display1);

function display1(){                              //displaying red background
    pressme.style.display = 'none';
    showme.style.display = 'block';
    button1.style.display=  'none';
    button2.style.display=  'block';
}


button2.addEventListener( 'mousedown', event => {
 timeout = setTimeout(() => {
   pressme.style.display = 'block';
   showme.style.display = 'none';
   button2.style.display=  'none';
   button1.style.display=  'block';
  }, 3000 );
});

button2.addEventListener( 'mouseup', event => {
    if ( timeout ) clearTimeout( timeout );
});
<!DOCTYPE html>
<html>
<head>
  <title>Realtime communication with WebRTC</title>
  <link rel="stylesheet" href="css/main.css" />
</head>
<body>


<table id="pressme" style="width:100%" bgcolor="red" height =500px>
        <button id="myBtn">Try it red</button>

    </table>


<table id="showme" style="width:100%;display:none;" bgcolor="green"height=500px>
        <button id="myBtn1" style=display:none; >Try it green </button>

</table>

</body>
</html>