Поместите курсор в конец <pre>, если contenteditible = true и выделите. js - PullRequest
0 голосов
/ 07 августа 2020

Я использую highlight. js для автоматического выделения кода в элементе <pre>. Я пытаюсь включить подсветку синтаксиса в реальном времени при наборе текста. Код, который у меня сейчас работает, работает должным образом, и выделение действительно работает при возврате каретки, но курсор перемещается в начало элемента <pre>. Я хотел бы переместить курсор в конец после того, как событие keyup обнаружит возврат каретки, и я повторно обработаю элемент, чтобы добавить подсветку синтаксиса. Как я могу выполнить sh это?

Пример находится здесь: https://tools.peer.ooo/snippity

Но код, который я использую для соответствующей части, таков:

document.addEventListener("keyup", function(e){
    if(e.keyCode == 13){
        document.querySelectorAll('pre').forEach((block) => {
            hljs.highlightBlock(block);

        })
    }
})

Как мне поместить курсор в конец существующего ввода?

Фрагмент кода

  document.addEventListener('DOMContentLoaded', async () => {
    document.querySelectorAll('pre').forEach((block) => {
      hljs.highlightBlock(block);
      block.classList.add("container")
    })
  })
  var db = new Dexie("snippits");
  db.version(1).stores({
    snippits: "++id, identifier, name, data, *tags"
  });

  document.getElementById("save").addEventListener("click", function() {

    let name = document.getElementById("snipname").value
    let data = document.getElementById("rendered").textContent
    db.snippits.add({
      identifier: "some id",
      name: name,
      data: data
    })
    document.querySelectorAll('pre').forEach((block) => {
      hljs.highlightBlock(block);
    })

  })

  document.getElementById("rendered").addEventListener("blur", function(e) {
    console.log("tabbed out")
    document.querySelectorAll('pre').forEach((block) => {
      hljs.highlightBlock(block);
    })
  })

  document.addEventListener('DOMContentLoaded', async () => {
    const data = await db.snippits.orderBy('id').last()

    console.log(JSON.stringify(data))
    document.getElementById("snipname").value = data.name
    document.getElementById("rendered").textContent = data.data
    document.querySelectorAll('pre').forEach((block) => {
      hljs.highlightBlock(block);
    })
  })

  function onPaste(e) {
    e.preventDefault(); // stop the paste
    const t = e.clipboardData.getData("text"); // grab the pasted content as plain text
    e.target.textContent = t; // set the element's innerHTML to the plain text
    document.querySelectorAll('pre').forEach((block) => {
      hljs.highlightBlock(block);
    })
  }

  document.addEventListener("keyup", function(e) {
    if (e.keyCode == 13) {
      document.querySelectorAll('pre').forEach((block) => {
        hljs.highlightBlock(block);
      })
    }
  })

  const paste = document.getElementById('rendered');
  paste.addEventListener('paste', onPaste);
 html {
    background: rgb(58, 58, 63)
  }

  pre {
    outline: none;
    min-height: 100px;
  }

  input {
    outline: none;
  }

  textarea {
    outline: none;
  }

  /* Comment */
  .hljs-comment,
  .hljs-quote {
    color: #989498;
  }

  /* Red */
  .hljs-variable,
  .hljs-template-variable,
  .hljs-attribute,
  .hljs-tag,
  .hljs-name,
  .hljs-selector-id,
  .hljs-selector-class,
  .hljs-regexp,
  .hljs-link,
  .hljs-deletion {
    color: #dd464c;
  }

  /* Orange */
  .hljs-number,
  .hljs-built_in,
  .hljs-builtin-name,
  .hljs-literal,
  .hljs-type,
  .hljs-params {
    color: #fd8b19;
  }

  /* Yellow */
  .hljs-class .hljs-title {
    color: #fdcc59;
  }

  /* Green */
  .hljs-string,
  .hljs-symbol,
  .hljs-bullet,
  .hljs-addition {
    color: #8fc13e;
  }

  /* Aqua */
  .hljs-meta {
    color: #149b93;
  }

  /* Blue */
  .hljs-function,
  .hljs-section,
  .hljs-title {
    color: #1290bf;
  }

  /* Purple */
  .hljs-keyword,
  .hljs-selector-tag {
    color: #c85e7c;
  }

  .hljs {
    display: block;
    overflow-x: auto;
    background: #322931;
    color: #b9b5b8;
    padding: 0.5em;
  }

  .hljs-emphasis {
    font-style: italic;
  }

  .hljs-strong {
    font-weight: bold;
  }
  
  
  
  
  
  


    
    
    
Сохранить Удалить Поделиться

1 Ответ

1 голос
/ 08 августа 2020

Как насчет этого?

document.addEventListener('DOMContentLoaded', async() => {
  document.querySelectorAll('pre').forEach((block) => {
    hljs.highlightBlock(block);
    block.classList.add("container")
  })
})
var db = new Dexie("snippits");
db.version(1).stores({
  snippits: "++id, identifier, name, data, *tags"
});

document.getElementById("save").addEventListener("click", function() {

  let name = document.getElementById("snipname").value
  let data = document.getElementById("rendered").textContent
  db.snippits.add({
    identifier: "some id",
    name: name,
    data: data
  })
  document.querySelectorAll('pre').forEach((block) => {
    hljs.highlightBlock(block);
  })

})

document.getElementById("rendered").addEventListener("blur", function(e) {
  console.log("tabbed out")
  document.querySelectorAll('pre').forEach((block) => {
    hljs.highlightBlock(block);
  })
})

document.addEventListener('DOMContentLoaded', async() => {
  const data = await db.snippits.orderBy('id').last()

  console.log(JSON.stringify(data))
  document.getElementById("snipname").value = data.name
  document.getElementById("rendered").textContent = data.data
  document.querySelectorAll('pre').forEach((block) => {

    hljs.highlightBlock(block);
  })
})

function onPaste(e) {
  e.preventDefault(); // stop the paste
  const t = e.clipboardData.getData("text"); // grab the pasted content as plain text
  e.target.textContent = t; // set the element's innerHTML to the plain text
  document.querySelectorAll('pre').forEach((block) => {
    hljs.highlightBlock(block);
  })
}

const editerElem = document.querySelector('#code-snippet')
editerElem.addEventListener('keyup', (evt) => {
   const val = evt.target.value;
   const outputPre = document.querySelector('#output')
   const output =  hljs.highlightAuto(val);
   outputPre.innerHTML = output.value;
})
/*
document.addEventListener("keyup", function(e) {
  if (e.keyCode == 13) {
    document.querySelector('pre')
      .forEach((block) => {
      const output = hljs.highlightBlock(block);
      block.focus();
    })
  }
})
*/
const paste = document.getElementById('rendered');
paste.addEventListener('paste', onPaste);
html {
  background: rgb(58, 58, 63)
}

#the-code-editor {
  display: flex;
  flex-direction: row;
}
#the-code-editor textarea, #the-code-editor pre {
  display: block;
  width: 50%;
}
pre {
  outline: none;
  min-height: 100px;
}

input {
  outline: none;
}

textarea {
  outline: none;
}


/* Comment */

.hljs-comment,
.hljs-quote {
  color: #989498;
}


/* Red */

.hljs-variable,
.hljs-template-variable,
.hljs-attribute,
.hljs-tag,
.hljs-name,
.hljs-selector-id,
.hljs-selector-class,
.hljs-regexp,
.hljs-link,
.hljs-deletion {
  color: #dd464c;
}


/* Orange */

.hljs-number,
.hljs-built_in,
.hljs-builtin-name,
.hljs-literal,
.hljs-type,
.hljs-params {
  color: #fd8b19;
}


/* Yellow */

.hljs-class .hljs-title {
  color: #fdcc59;
}


/* Green */

.hljs-string,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
  color: #8fc13e;
}


/* Aqua */

.hljs-meta {
  color: #149b93;
}


/* Blue */

.hljs-function,
.hljs-section,
.hljs-title {
  color: #1290bf;
}


/* Purple */

.hljs-keyword,
.hljs-selector-tag {
  color: #c85e7c;
}

.hljs {
  display: block;
  overflow-x: auto;
  background: #322931;
  color: #b9b5b8;
  padding: 0.5em;
}

.hljs-emphasis {
  font-style: italic;
}

.hljs-strong {
  font-weight: bold;
}








  
  
  
  
  Сохранить  Удалить  Поделиться        

Удачи ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...