javascript - 创建按钮 onclick 函数以充当箭头键的作用

标签 javascript html button input onclick

我有一个充当退格键的 Java 脚本函数。这工作正常,但现在我想创建一个返回按钮和一个前进按钮而不删除文本(就像箭头键的行为)。非常感谢任何对此的帮助。

 function setBack() {
     document.getElementById('user').value = 
     document.getElementById('user').value.substring(0, 
     document.getElementById('user').value.length - 1);
 }
 <input id="user" type="text">
 <button type="button" onclick="setBack();">backspace</button>
 <button type="button" onclick="">back</button>
 <button type="button" onclick="">forward</button>

没有 jQuery,请仅使用 Native Javascript。

最佳答案

尝试一下:

       
            let input = document.getElementById('Test');
            input.focus();
              
            let index = 0;

            document.getElementById('Prev').addEventListener('click', function(){
                
                index -= 1;
                
                if(index <= 0) {
                    index = input.value.length;
                }

                input.focus();
                input.selectionEnd = index;
                input.selectionStart = index;
            });


            document.getElementById('Next').addEventListener('click', function(){
                console.log(index);
                
                index += 1;
                
                if(index > input.value.length) {
                    index = 0;
                }

                input.focus();
                input.selectionEnd = index;
                input.selectionStart = index;
            });
        <input id="Test" type="text" value="helloooo">
        <button id="Prev">Prev</button>
        <button id="Next">Next</button>

关于javascript - 创建按钮 onclick 函数以充当箭头键的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49437368/

相关文章:

asp.net - 如何在 ASP.NET Web 应用程序中使用 .psd 分层按钮

Javascript 通过按钮关闭该功能

javascript - 如果发生无效输入,如何使函数返回到特定位置?

html - 不影响 HTML 文档的 CSS 代码

javascript - 如何在 UI 控件中获取地形图 HERE Maps v3.1

javascript - 在 Express 中接收 POST 请求时登录

javascript - 如何通过html5音频元素从php播放音频文件

button - Office Fabric UI - onClick IconButton 在打包解决方案时不起作用

javascript - 对象传播符号如何转换 react redux Prop ?

javascript - 页面上的多个选项卡区域