<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding: 0; } .div2{ width: 400px; height: 250 ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
.div2{
width: 400px;
height: 250px;
border: 1px solid red;
}
.div2 li{
list-style: none;
float: left;
width: 85px;
height: 25px;
background-color: lightgray;
margin-left:12px ;
margin-top: 30px;
text-align: center;
cursor: pointer;
}
.div3 {
width: 300px;
height: 100px;
border: 1px solid red;
position: absolute;
right: 300px;
top: 100px;
}
</style>
</head>
<body>
<div class="div2">
<ul id="ul">
</ul>
</div>
<div class="div3">
標題:<input type="text" id="title"><br>
顏色:<input type="text" id="color"><br>
字體:<input type="text" id="size"><br>
<input type="button" value="添加" onclick="f1()"><br>
</div>
</body>
</html>
<script>
var array=[];
function f1(){
//獲取輸入的顏色
var color=document.getElementById("color").value;
//獲取輸入的標題
var title=document.getElementById("title").value;
//獲取輸入的字體
var size=document.getElementById("size").value;
var item={
title:title,
color:color,
size:size
};
array.push(item);
var str="";
for( var i=0;i<array.length;i++){
str+="<li style='color:"+array[i].color+";font-size:"+array[i].size+"'>" +array[i].title + "</li>";
}
var ul=document.getElementById("ul");
ul.innerHTML=str;
//更新存儲
var str= JSON.stringify(array);
localStorage.setItem("key1",str);
}
//將讀取出來的json字元串在轉成原數組
var jstr= localStorage.getItem("key1");
var array=JSON.parse(jstr);
var str="";
for( var i=0;i<array.length;i++){
str+="<li style='color:"+array[i].color+";font-size:"+array[i].size+"'>" +array[i].title + "</li>";
}
var ul=document.getElementById("ul");
ul.innerHTML=str;
</script>