检测按键而忽略修饰键

时间:2019-11-15 06:32:31

标签: javascript

我正在为我的网站实现空闲超时功能。每当用户与页面互动时,我都想重置空闲超时,我想将其实现为“用户单击页面上的任意位置”或“用户键入键”。

以下代码有效:

window.addEventListener('click', resetTimeout);
window.addEventListener('keydown', resetTimeout);

不幸的是,它检测到修饰键(alt,shift,ctrl,meta)。在这些情况下,我不想重置超时。例如,当用户alt + tab转到另一个窗口时,alt键将重置超时。

keydown的替代方法是keypress,但是marked as deprecatedkeypress是否有替代方法,专门针对我所描述的情况?

3 个答案:

答案 0 :(得分:1)

注释到排除键中,您可以添加所有不需要的键。您可以在这里搜索它们:https://www.w3.org/TR/uievents-key/

let excludedKeys = ["Alt"];
window.addEventListener('keydown', e => {
  if(!excludedKeys.includes(e.key)) resetTimeout();
});

答案 1 :(得分:1)

您需要一个变量来保持true / false,该变量告诉您​​是否按住了被忽略的键,如果是,则可以忽略所有将重置计时器的keydown事件。释放被忽略的键后,您可以侦听键按下事件。

这是一个小演示:

<section id="about-us">
  <div class="container">
    <img src="https://app.sellerseo.com/uploads/print_logo.png" alt="" />
    <p>
              Huatai Securities Co.,Ltd. is a leading integrated securities group in
              China, with a substantial customer base, a leading e-Platform and a
              highly collaborative full-service business model.
    </p>
    <p>
              Huatai Securities was established in May 1991.On February 26, 2010, we
              were listed at Shanghai Stock Exchange with the stock code of 601688.
              On June 1, 2015, our H Shares have been listed on The Stock Exchange
              of Hong Kong Limited with the stock code of 6886. Over our more than
              two decades of operating history, we achieved rapid growth by
              successfully capitalizing on the transformation and innovation
              opportunities of China's capital market and securities industry. Our
              major financial indicators and business indicators are among the
              forefront of the domestic securities industry.
    </p>
    <p>
              Currently, Huatai Securities has controlling interests in 3
              subsidiaries including Huatai United Securities Co., Ltd., Huatai
              Futures Co.,Ltd., and Jiangsu Equity Exchange Co., Ltd. We have 4
              wholly owned subsidiaries including Huatai Financial Holdings(Hong
              Kong) Limited, Huatai Zijin Investment Co., Ltd., Huatai Innovation
              Investment Co., Ltd., and Huatai Securities (Shanghai) Asset
              Management Co., Ltd. We also have minority interests in China Southern
              Asset Management Co., Ltd., Huatai-PineBridge Fund Management Co.,
              Ltd., Bank of Jiangsu Co., Ltd., GP Capital Co., Ltd., and E-Capital
              Transfer Co., Ltd.
    </p>
    <p>
              During recent years, Huatai Securities has focused on providing
              customers with the full life-cycle integrated financial services. We
              have built a full-service business model which is led by investment
              banking, underpinned by brokerage and wealth management and supported
              by asset management as well as investment and trading.
    </p>
    <p>
              Huatai Securities has the largest securities brokerage business in
              China and a leading e-Platform in the industry. We ranked No.1 in
              terms of brokerage trading volume of stocks and funds in China's
              securities industry in 2014.As of the end of 2014, the number of our
              securities brokerage accounts ranked No.1 among all China's securities
              firms; and the balance of our margin loans and securities lent ranked
              No.2 and the market value of our client entrusted securities ranked
              No.3 in China's securities industry. Our mobile wealth management
              terminal, “ZhangLe Fortune Path”, was rated No.1 by Sina.com in its
              review of mobile securities apps in 2014.
    </p>
    <p>
              Huatai Securities has a leading comprehensive investment banking
              franchise and the top M&A advisory business in the industry. In terms
              of the number of CSRC-approved M&A advised by us, we have been ranked
              No.1 in the industry for the three consecutive years since 2012. In
              2014, our equity and debt underwriting businesses also ranked among
              the top ten securities firms in China, in terms of both value and
              number of transactions underwritten.
    </p>
    <p>
              Huatai Securities also has one of the largest comprehensive asset
              management businesses in China's securities industry, with leading
              product innovation capability. The AUM of our collective asset
              management schemes as of the end of 2014 and the net revenue from our
              asset management business in 2014 ranked No.2 and No.3, respectively,
              in China's securities industry.
    </p>
    <p>
              From now on, we plan to leverage our competitive advantages in the
              securities business to expand our full-service operations, and aim to
              become a leading integrated financial group which has a profound
              impact in Asia-Pacific Market with strong local advantages and a
              global vision.
    </p>
   </div>
</section>
const display = document.getElementById('status');

let idleTime = 0;
const timer_cb = _ => {
  if(idleTime > 5) {
    display.innerText = "You are now idle";
    clearInterval(timer);
  } else {
    display.innerText = "You have been inactive for: " + idleTime +" seconds";
    idleTime++;
  }
}

let timer = setInterval(timer_cb, 1000);

const ignoreKeys = new Set(['Meta', 'Control', 'Shift', 'Alt']);
let ignore = false;

const resetTimeout = ({key}) => {
  ignore = ignore || ignoreKeys.has(key);
  if(!ignore) {
    idleTime = 0;
    timer_cb();
    clearInterval(timer);
    timer = setInterval(timer_cb, 1000);
  }
};

const acknowledge = ({key}) => {
  ignore = !!(ignore ^ ignoreKeys.has(key));
}

window.addEventListener('click', resetTimeout);
window.addEventListener('keydown', resetTimeout);
window.addEventListener('keyup', acknowledge);
timer_cb();

答案 2 :(得分:-2)

添加功能并检查命令键,如下所示:

document.addEventListener("keydown", function(event) {
  event.preventDefault();
  const key = event.keyCode; //You can also use event.key to get the text value. e.g. "Alt", "Ctrl"
  if(key != 17 && key != 18) //Alt and Ctrl keys. key should not 17 as well as 18 then resetTimeOut.
  {
       resetTimeout();
  }
});

如果要使用.key,则可以使用字符串,并检查该字符串中是否存在所按下的键。

document.addEventListener("keydown", function(event) {
      event.preventDefault();
      const key = event.key
      if(! "Alt,Control,Tab".split(",").includes(key))
      {
           resetTimeout();
      }
    });