让前端飞

html5本地存储localStorage(搜索栏)

2019-02-18  本文已影响15人  yuanzhuang

本地存储localstorage(搜索框)

呈现的样式

内容

与下面衔接

可复制代码

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>Document</title>

</head>

<style>

  * {

    padding: 0;

    margin: 0;

  }

  #ul {

    display: none;

    position: absolute;

    width: 170px;

    top: 26px;

    background-color: #ccc;

  }

</style>

<body>

  <input type="text" id="inp">

  <button id="btn">点击搜索</button>

  <button id="del">删除历史记录</button>

  <ul id="ul">

  </ul>

</body>

<script>

  var btn = document.getElementById('btn')

  var inp = document.getElementById('inp')

  var ul = document.getElementById("ul")

  var arr = []

  var val = null

  btn.onclick = function () {

    if (inp.value.trim().length !== 0) {

      val = inp.value

      inp.value = " "

      arr.push(val)

      var str = arr.join(',')

      localStorage.setItem('a', str)

      disappear()

    } else {

      alert('请输入内容')

    }

  }

  if (localStorage.getItem('a')) {

    str = localStorage.getItem('a')

    arr = str.split(",")

    Splicing()

  }

  inp.onclick = function () {

    ul.style.display = "block"

    Splicing()

    var tash = document.querySelectorAll("#ul>li")

    for (var i = 0; i < tash.length; i++) {

      tash[i].onclick = function () {

        inp.value = this.innerHTML

        disappear()

      }

    }

  }

  document.onmouseup = function () {

    disappear()

  }

  document.getElementById('del').onclick = function () {

    localStorage.removeItem("a")

    arr = []

    str = ""

    ul.innerHTML = ""

  }

  function Splicing() {

    var li = " "

    for (var i = 0; i < arr.length; i++) {

      li += "<li>" + arr[i] + "</li>"

    }

    ul.innerHTML = li

  }

  function disappear() {

    ul.style.display = "none"

  }

</script>

</html>

上一篇 下一篇

猜你喜欢

热点阅读