【发布时间】:2020-03-07 00:05:02
【问题描述】:
如何使用 jQuery 制作按钮在文本区域中向上、向下、向左或向右移动光标?
$(document).ready(function() {
var clpBrd;
$("textarea")[0].focus(); /*To show to cursor at the end of text*/
$("#cpBtn").click(function(){
clpBrd = $("txtOutput").text();
console.log("COPIED: "+clpBrd);
});
$("#ltBtn").click(function(){
var txtVal = $("textarea").val();
var txtLen = txtVal.length;
$("textarea")[0].focus(txtLen - 1);
});
$("#rtBtn").click(function(){
var txtVal = $("textarea").val();
var txtLen = txtVal.length;
$("textarea")[0].focus(txtLen + 1);
});
$("#upBtn").click(function(){
var txtVal = $("textarea").val();
var txtLen = txtVal.length;
$("textarea")[0].focus( /*??*/ );
});
$("#dnBtn").click(function(){
var txtVal = $("textarea").val();
var txtLen = txtVal.length;
$("textarea")[0].focus(/*??*/);
});
var selPressed = false;
$("#selBtn").click(function(){
selPressed = !selPressed;
});
});
* {
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
width: 100vw;
height: 100vh
}
textarea,
#btnWrap button {
display: flex;
flex-grow: 1;
}
textarea::selection{
color:white; background: black
}
#btnWrap {
height: 50px;
display: flex;
flex-direction: row;
}
#btnWrap button {
align-items: center;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="txtOutput">
Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.</textarea>
<div id="btnWrap">
<button id="slBtn">Select</button>
<button id="upBtn">▲</button>
<button id="ltBtn">◀</button>
<button id="rtBtn">▶</button>
<button id="dnBtn">▼</button>
<button id="ctBtn">Cut</button>
<button id="psBtn">Paste</button>
<button id="cpBtn">Copy</button>
</div>
另外,我们如何使用向上/向下按钮选择文本?
如果selPressed 为真,则移动光标将选择文本。否则它只是移动光标。
我认为使用数组进行剪切/复制/粘贴会很困难。
我是否必须使用像 clipboard.js 这样的外部库,或者没有它可以做到这一点吗?
【问题讨论】:
-
你应该看看Selection API
标签: javascript jquery button custom-keyboard textselection