| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title></title>
- <style>
- * {
- margin: 0;
- padding: 0;
- }
- #container {
- margin: 20px 50px;
- }
- #fruits li {
- list-style: none;
- width: 200px;
- height: 50px;
- font-size: 20px;
- line-height: 50px;
- background-color: cadetblue;
- color: white;
- text-align: center;
- margin: 2px 0;
- }
- #fruits>li>a {
- float: right;
- text-decoration: none;
- color: white;
- position: relative;
- right: 5px;
- }
- #fruits~input {
- border: none;
- outline: none;
- font-size: 18px;
- }
- #fruits~input[type=text] {
- border-bottom: 1px solid darkgray;
- width: 200px;
- height: 50px;
- text-align: center;
- }
- #fruits~input[type=button] {
- width: 80px;
- height: 30px;
- background-color: coral;
- color: white;
- vertical-align: bottom;
- cursor: pointer;
- }
- </style>
- </head>
- <body>
- <div id="container">
- <ul id="fruits">
- <li>苹果<a href="">×</a></li>
- <li>香蕉<a href="">×</a></li>
- <li>火龙果<a href="">×</a></li>
- <li>西瓜<a href="">×</a></li>
- </ul>
- <input type="text" name="fruit">
- <input id="ok" type="button" value="确定">
- </div>
- <script src="js/common.js"></script>
- <script>
- function removeItem(evt) {
- evt = evt || window.event;
- prevent(evt); // 用自定义函数阻止事件的默认行为
- var target = evt.target || evt.srcElement;
- var li = target.parentNode;
- li.parentNode.removeChild(li);
- }
-
- (function() {
- function addItem(evt) {
- var fruitName = textInput.value.trim();
- if (fruitName.length > 0) {
- var li = document.createElement("li");
- li.textContent = fruitName;
- li.style.backgroundColor = "rgba(20, 150, 180, 0.5)";
- var a = document.createElement("a");
- a.href = "";
- a.textContent = "×";
- bind(a, "click", removeItem);
- li.appendChild(a);
- var ul = document.getElementById("fruits");
- ul.insertBefore(li, ul.children[0]);
- }
- textInput.value = "";
- textInput.focus();
- }
-
- var anchors = document.querySelectorAll("#fruits>li>a");
- for (var i = 0; i < anchors.length; i += 1) {
- bind(anchors[i], "click", removeItem);
- }
- var btn = document.getElementById("ok");
- var textInput = document.getElementsByName("fruit")[0];
- bind(textInput, "keyup", function(evt) {
- evt = evt || window.event;
- var code = evt.keyCode || evt.which;
- // console.log(code);
- if (code == 13) {
- addItem();
- }
- });
- bind(btn, "click", addItem);
- })();
- </script>
- </body>
- </html>
|