我已经在JavaScript中构建了此窗口的高度和宽度显示功能(类似于Chrome DevTools中的功能)。它是这样的:


如果您调整窗口的宽度/高度,它将在附加的文本框中显示当前的屏幕尺寸。
如果该窗口在3秒钟内处于非活动状态,则文本框将隐藏。
如果您重新调整窗口,它将重置计时器(以免造成重叠,以防您在1-2秒内重新调整)。


可行,这是我的第三次重写,但是我知道它的编码可以比这更好,有人可以给我一些有关如何改进代码的建议吗?我仍处于新秀阶段。

https://jsfiddle.net/kon56edn/

var boxText = document.createElement('div');
var boxStyle = boxText.style;

boxStyle.position = 'fixed';
boxStyle.right = 0;
boxStyle.top = 0;
boxStyle.padding = '16px';
boxStyle.zIndex = 999;
boxStyle.fontSize = '22px';
boxStyle.display = 'none';

var timerHandle = setTimeout(3000);

function resetTimer() {
  window.clearTimeout(timerHandle);

timerHandle = setTimeout(function() {

  boxStyle.display = 'none';

 }, 3000);
}

window.addEventListener('resize', function(timerHandle) {

  boxText.innerText = window.innerWidth + 'px' + ' x ' + window.innerHeight + 'px';
  boxStyle.display = 'block';
  document.body.appendChild(boxText);

  resetTimer();

});


我真的想在编写干净的模块化JS方面变得更好。任何帮助或观点表示赞赏! :-)

最佳答案

您有一些错误,主要是在事件处理程序上进行了一些繁重的工作。
这是一个较轻的版本

var box = document.createElement('div');
var timerHandle;

// I would move this to external css if you want cleaner code
box.style.position = 'fixed';
box.style.right = 0;
box.style.top = 0;
box.style.padding = '16px';
box.style.zIndex = 999;
box.style.fontSize = '22px';
box.style.display = 'none';

// Append the box to the view only once! not everytime the event occures
document.body.appendChild(box);

// Handler for when the time is up
function hideBox() {
    box.style.display = 'none';
}

// I would add a throttle function here, search for lodash throttle for example
window.addEventListener('resize', function() {
    box.innerText = window.innerWidth + 'px' + ' x ' + window.innerHeight + 'px';
    box.style.display = 'block';

    // Reset the timer everytime the event happens
    if (timerHandle) {
        clearTimeout(timerHandle);
        timerHandle = null;
    }

    // Start the timer only when the event happend
    timerHandle = setTimeout(hideBox, 3000);
});

10-01 16:36
查看更多