Как сохранить ie повара одним нажатием кнопки? - PullRequest
1 голос
/ 05 мая 2020

Я планировал добавить на свой веб-сайт функцию перетаскивания заметок и сохранить ее в javascript cook ie. Кроме того, я хотел сохранить textarea как переменную, а переменную как cook ie ... Я не хочу использовать локальное хранилище. Если вы видите на той части, где находится элемент div, есть кнопка. Я действительно не знаю, как поместить переменную из текстового поля на повар ie, поэтому, когда вы нажимаете на переменную, он сохраняет текст внутри текстового поля как переменную, а затем сохраняет переменную как повар ie. Итак, когда вы перезагружаете страницу, она вставляет повар ie в текстовое поле. Я хотел сделать что-то вроде этого:

<!DOCTYPE html>
<html>
<style>
#notes {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #d3d3d3;
}

#notesheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
</style>
<body>


<div id="notes">
  <div id="notesheader">Notes</div>
  <textarea rows="4" cols="50"></textarea>
  <br>
  <button onclick="document.cookie = "username= Notes";">Save</button>
</div>

<script>
//Make the DIV element draggable:
dragElement(document.getElementById("notes"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
</script>
<button onclick="hideshow()">Notes</button>
<script>
function hideshow() {
  var x = document.getElementById("notes");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
</body>
</html>


Есть ли решение для этого?

Ответы [ 2 ]

0 голосов
/ 05 мая 2020

Чтобы получить значение textarea, вам просто нужно запросить его и получить его значение. тогда вы должны использовать document.cookie, чтобы установить желаемое приготовление ie.

Create cook ie

Поэтому всякий раз, когда нажимается кнопка сохранения, вы должны запускать такую ​​функцию:

HMTL

<div id="notes">
  <div id="notesheader">Notes</div>
  <textarea id="notes" rows="4" cols="50"></textarea>
  <br>
  <button onclick="saveNotes();">Save</button>
</div>

Javascript

function saveNotes() {
  document.cookie = "textAreaValue=" + document.getElementById("notes").value
}

Читать повар ie

Чтобы прочитать повар ie из браузера , вам нужно получить значение document.cookie и ввести желаемое значение из это (так как он держит все варки домена ie). Получить файлы cookie по имени немного сложно, поскольку document.cookie вернет все файлы cookie в домене, поэтому мы должны определить две функции для этой причины. Сначала функция для получения cook ie по желаемому имени и еще одна функция для отслеживания загрузки окна, а затем загрузка cook ie в наши элементы.

Ваш код должен быть примерно таким:

function getCookie(cookieName) {
  var name = cookieName + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

window.onload = function() { // window.onload will indicate when the window is loaded do this function
  var textAreaFromCookie = getCookie("textAreaValue")

  if (textAreaFromCookie) {
    document.getElementById('notes').value = textAreaFromCookie
  }
};
0 голосов
/ 05 мая 2020

Проблема в том, что вы использовали " внутри строки, состоящей из " s, без экранирования. Используйте строку с ' s или избегайте кавычек:

<!DOCTYPE html>
<html>
<style>
#notes {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #d3d3d3;
}

#notesheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
</style>
<body>


<div id="notes">
  <div id="notesheader">Notes</div>
  <textarea rows="4" cols="50"></textarea>
  <br>
  <button onclick="document.cookie = 'username= Notes';">Save</button>
</div>

<script>
//Make the DIV element draggable:
dragElement(document.getElementById("notes"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
</script>
<button onclick="hideshow()">Notes</button>
<script>
function hideshow() {
  var x = document.getElementById("notes");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...