使用键盘和鼠标更改字体大小

Changing font size using keyboard and mouse

本文关键字:字体 鼠标 键盘      更新时间:2023-09-26

我正试图通过按下某些按钮来更改字体大小。例如:

  1. "Alt"answers"+"
  2. Esc

当涉及到Esc按钮时,我遇到了问题。我知道Esc键Code是27,但它似乎不起作用。我甚至试着使用onkeyup,但也无济于事。基本上,当我按下Esc按钮时,它应该将文本返回到30pt的起始位置。如果我能回答这个问题,我将不胜感激。

<html>
<head>
<style>p{font-size: 30pt;}</style>
</head>
<body onmousedown="changeSize(event)" onkeyup="changeSize(event)">
     <p>Text1</p>
     <p>Text2</p>
     <p>Text3</p>
</body>
<script>
    var start = 30;
    var min = 10;
    var max = 50;
    function changeSize(e) {
    var b = e.keyCode;
    var c = e.button; 
    var fontSized = document.getElementsByTagName("p");
    if (e.altKey){
            if (b == 107){
                if (start <=max && start >=min){
                start += 5;
                    for (i=0; i<=fontSized.length; i++){
                        fontSized[i].style.fontSize = start + "pt";
                    };  
                } 
            }
        }
    if (b == 27){
        start = 30;
        for (i=0; i<=fontSized.length; i++){
            fontSized[i].style.fontSize = start + "pt";
        };  
    }
    }
</script>
</html>

您的if (b == 27) {位于if (e.altKey) {块内,因此只有同时按下alt时它才会工作。你的代码应该是这样的:

if (e.altKey){
    if (b == 107){
        if (start <=max && start >=min){
            start += 5;
            for (i=0; i<=fontSized.length; i++){
                fontSized[i].style.fontSize = start + "pt";
            };  
        } 
    }
}
if (b == 27){
    start = 30; // start == 30 is a comparator, and does not set start to 30
    for (i=0; i<=fontSized.length; i++){
        fontSized[i].style.fontSize = start + "pt";
    };  
}

注意,if (b == 27)之后的start == 30已更改为start = 30

编辑:尝试代码后,一切似乎都正常工作,但要增加字体大小,必须执行Alt+'+'(在数字键盘上!)。您可能需要考虑使用Alt+Shift+'='或只使用Alt+'='

作为参考,这里是我的代码:

<html>
<head>
<style>p{font-size: 30pt;}</style>
</head>
<body onmousedown="changeSize(event)" onkeyup="changeSize(event)">
     <p>Text1</p>
     <p>Text2</p>
     <p>Text3</p>
</body>
<script>
    var start = 30;
    var min = 10;
    var max = 50;
    function changeSize(e) {
    var b = e.keyCode;
    var c = e.button; 
    var fontSized = document.getElementsByTagName("p");
    if (e.altKey) {
        if (b == 187){ // Now the combination is Alt + '='
            if (start <=max && start >=min){
                start += 5;
                    for (i=0; i<=fontSized.length; i++){
                        fontSized[i].style.fontSize = start + "pt";
                    };  
            } 
        }
    }
    if (b == 27){
            start = 30;
            for (i=0; i<=fontSized.length; i++){
                fontSized[i].style.fontSize = start + "pt";
            };  
        }
    }
</script>
</html>

在这种情况下,通常需要阻止事件传播,因为它将遍历所有父级,直到到达浏览器。