I am making a typewriter-like website (here) that uses a textarea and javascript (from button clicks) to add/remove from the textarea.
在遵循这 2 个答案(1、2)之后,我现在使用默认的打字指示器来显示文本位置。
为了防止用户点击 textarea
中的其他位置,我将 pointer-events:none
添加到 textarea
的 css,但是这也会阻止突出显示部分或全部文本以手动复制它。
这是文本区域
<textarea id="textarea" class="textarea" data-gramm_editor="false" data-gramm="false">
</textarea>
用这个CSS
.textarea {
pointer-events:none;
font-size: 23px;
width: 100%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
resize: none;
}
视觉解释:我希望能够像this一样选择无法点击并执行此操作 this .
有没有办法把点击和高亮分开,只屏蔽点击?
如果解决方案无法在移动设备上顺利运行,但仍然可以,请指出/解释。
最佳答案
好的,我编辑了我之前的回答:
如果我理解正确,你想保持突出显示(选择文本)但不要让用户在文本区域上移动光标。如果是这样,那么你可以做这样的事情。首先让我们删除
pointer-events:none;
然后在textarea上添加readonly
例子:
<textarea readonly id="textarea" class="textarea" data-gramm_editor="false" data-gramm="false">
</textarea>
注意:通常避免使用 pointer-events: none
它会禁用突出显示和选择以及光标样式。
现在在你的情况下(激活选择,激活光标,不要让用户在 textarea 中移动光标),你可以做类似的事情,你可以使用 div
而不是 textarea
并编辑该 div 的 inneHTML。如您所见,我创建了一个 html 元素的光标,它类似于真正的光标。通过这样做,您可以更好地控制键盘,希望对您有所帮助。
通常,仅使用 textarea
是不可能实现所有您想要的。
const editable = document.getElementById('editableC');
addCursor()
const buttons = document.querySelectorAll('button');
buttons.forEach(el =>
el.addEventListener('click', event => {
removeCursor();
const letter = event.target.innerHTML;
if (letter === 'clear') {
editable.innerHTML = editable.innerHTML.slice(0, -1);
}else {
editable.innerHTML += letter;
}
addCursor()
})
);
function addCursor(){
let span = document.createElement('span');
span.classList.add('blinking-cursor');
let text = document.createTextNode('|');
span.appendChild(text);
editable.appendChild(span);
}
function removeCursor(){
const span = editable.querySelector('span')
span.remove()
}
.editableC {
width: 300px;
height: 100px;
border: 1px solid #ccc;
padding: 5px;
word-break: break-all;
}
.blinking-cursor {
user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
font-size: 18px;
margin-left: 2px;
color:red;
-webkit-animation: 1s blink step-end infinite;
-moz-animation: 1s blink step-end infinite;
-ms-animation: 1s blink step-end infinite;
-o-animation: 1s blink step-end infinite;
animation: 1s blink step-end infinite;
}
@keyframes "blink" {
from,
to {
color: transparent;
}
50% {
color: red;
}
}
@-moz-keyframes blink {
from,
to {
color: transparent;
}
50% {
color: red;
}
}
@-webkit-keyframes "blink" {
from,
to {
color: transparent;
}
50% {
color: red;
}
}
@-ms-keyframes "blink" {
from,
to {
color: transparent;
}
50% {
color: red;
}
}
@-o-keyframes "blink" {
from,
to {
color: transparent;
}
50% {
color: red;
}
}
<div id="editableC" class="editableC"></div>
<div style="margin-top:10px">
<button>A</button>
<button>B</button>
<button>clear</button>
</div>
关于javascript - 禁用光标点击而不阻止突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68582036/